package org.ezplatform.office.forum.service;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.cloud.common.service.ConfigService;
import org.ezplatform.cloud.common.util.LogUtils;
import org.ezplatform.component.permission.service.CmpApplyScopeService;
import org.ezplatform.component.popuser.service.CmpPopUserOrgName;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.security.SecurityUtils;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.mobile.util.message.service.MobileMessageService;
import org.ezplatform.office.forum.dao.ForumBoardDao;
import org.ezplatform.office.forum.dao.ForumPostDao;
import org.ezplatform.office.forum.dao.ForumPostLabelDao;
import org.ezplatform.office.forum.dao.ForumSensitiveDao;
import org.ezplatform.office.forum.entity.ForumBoard;
import org.ezplatform.office.forum.entity.ForumPost;
import org.ezplatform.office.forum.entity.ForumPost.CheckStatusEnum;
import org.ezplatform.office.forum.entity.ForumPostLabel;
import org.ezplatform.office.forum.entity.ForumSensitive;
import org.ezplatform.office.forum.util.forumpostsend.ForumPostSendUtils;
import org.ezplatform.office.forum.util.sensitiveword.SensitiveUtils;
import org.ezplatform.util.DateUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.SqlUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

/**
 *  我的论坛service
 * 2019年11月2日17:40:59
 * @author Administrator
 *
 */
@Service
@Transactional
public class ForumPostService extends BaseService<ForumPost, String> {

	private final Logger LOGGER = LoggerFactory.getLogger(ForumPostService.class);
    
    /**
     * modelCode forun
     */
    public final static String modelCode = "stdForum";
    
    /**
     * 消息umc_module中module_code的数据
     */
    public final static String pushCode = "forum";
    
    @Autowired
	private ForumBoardDao forumBoardDao;
    
    @Autowired
   	private CmpApplyScopeService cmpApplyScopeService;
        
    @Autowired
    private ConfigService configService;

	@Autowired
	private ForumPostDao forumPostDao;
	@Lazy
	@Autowired
	private ForumBoardService forumBoardService;
	@Lazy
	@Autowired
	private ForumLabelService forumLabelService;

	@Autowired
	private RestClient restClient;
	
	@Autowired
	private ForumPostLabelDao forumPostLabelDao;

	@Lazy
	@Autowired
	private ForumPostStatisticsService forumPostStatisticsService;

	@Autowired
	private AttachmentUtilsService attachmentUtilsService;
	
	@Autowired
    private AttachmentUtilsService attchService;

	@Autowired
	private UserApiService userApiService;
	
	@Autowired
	private PopUserScopeUtilService popUserScopeUtilService;
	
	@Autowired
	private ForumPostLabelService forumPostLabelService;
	
	@Autowired 
	private ForumSensitiveDao forumSensitiveDao;
	
	@Autowired
	private MobileMessageService mobileMessageService;
	
	@Autowired
	private LogService logService;
	
	@Autowired
	private ForumIntegralService forumIntegralService;
	
	@Autowired
	private CmpPopUserOrgName cmpPopUserOrgName;

	@Override
	protected JpaBaseDao<ForumPost, String> getEntityDao() {
		return forumPostDao;
	}

	/**
	 * 帖子类型----新帖
	 */
	public final static int POST_TYPE_NEW = 1;
	/**
	 * 帖子类型----发帖
	 */
	public final static int POST_TYPE_REPLY = 2;
	
	/**
	 * 帖子类型 ---评论
	 */
	public final static int POST_TYPE_REPLY_COMMENTS = 3;
	
	/**
	 * 回帖时的默认主题公共部分
	 */
	public final static String POST_REPLY_TITLE = "Re:";

	
	/**
	 * @param pageable
	 * @param filter
	 * @param corpId
	 * @param checkStatus 
	 * @return
	 * @Title: myPostList
	 * @Description: 分页获取“我的帖子”页面信息
	 * @return: Page<Map>
	 * @date 2017年11月21日 下午3:59:56
	 */
	public Page<Map> myPostList(Pageable pageable, List<PropertyFilter> filter, String token, String corpId,
			String type,String appType,String title, String checkStatus, String startTime ,String endTime) {
		WebUser user = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		StringBuffer sql = new StringBuffer();
		Map<String, Object> values = new HashMap<String, Object>();
		sql.append(" select a.id, a.attId,a.content,a.title, a.boardId, a.author ,a.postId,a.isCollection, fn_date_format(a.createdDate,'MM-dd HH:mm') createdDate,fn_date_format(a.publishTime,'yyyy-MM-dd HH:mm') publishTime, a.type, a.checkStatus, a.entityId,a.typeName, a.boardName, a.boardIsDelete,a.boardStatus,a.typeStatus,a.isCheck, a.lastReplyUser, fn_date_format(a.lastReplyDate,'yyyy-MM-dd HH:mm') lastReplyDate, a.view_count, a.reply_count, a.editPost ");
		sql.append(" from ( ");
		sql.append(" select t.id,t.attId,t.content, t.title, t.boardId, t.author,t.postId,t.isCollection, t.createdDate,t.publishTime, t.type, t.checkStatus, t.entityId, t.editPost,");
		sql.append(" type1.name as typeName, type1.status as typeStatus,b.name as boardName,b.is_delete as boardIsDelete, b.status AS boardStatus,b.is_check as isCheck, s.last_reply_user as lastReplyUser, s.last_reply_date as lastReplyDate, s.view_count, s.reply_count ");
		sql.append(" from ( ");
		sql.append(" select p.id,p.att_id attId,p.content,p.check_status as checkStatus,p.publish_time as publishTime");
		if("1".equals(type)) {
			sql.append(" ,case when ofs.id is null then 0 else 1 end as isCollection ");
		}else {
			sql.append(" ,p.is_collection as isCollection ");
		}
		sql.append(" , p.title, p.board_id as boardId, p.author, p.post_id as postId, p.createdDate, p.type, p.id as entityId, p.is_edit_post as editPost ");
		sql.append(" from oa_forum_post p ");
		if("1".equals(type)) {
			sql.append(" left join oa_forum_scope ofs on ofs.fieldDataValue = p.is_collection and ofs.scopeValue = :author ");
		}
		
		sql.append(" where p.corp_id = :corpId and p.author = :author and p.is_delete = 0 and p.type in (:type) ");
		sql.append(" ) t ");
		//对我发表的进行修改,被删除的版块下存在的审核未通过的帖子也要显示出来(由于版块下存在状态为审核中,审核通过,无需审核的就无法删除版块-->被删除版块下帖子没被删除的只剩下未通过的和草稿,草稿这里不需要,所以断定这里只需要把is_delete判定就可以)
		//2.3版本,我的帖子可以显示被禁用得版块下的帖子 但不能编辑;如果版块既被删除又被禁用,帖子也不能编辑
		if("1".equals(type) && !"1".equals(checkStatus) ) {
			sql.append(" inner join oa_forum_board b on t.boardId = b.id and b.status = 1 ");
		}else {
			//2.4我回复的显示版块被禁用下帖子
			sql.append(" inner join oa_forum_board b on t.boardId = b.id and b.is_delete = 0 and b.status = 1 ");
			//sql.append(" and b.status = 1 ");
		}
		sql.append(" inner join oa_forum_type type1 on b.forum_type = type1.id and type1.is_delete = 0  ");
		//sql.append(" left join  ");
		//sql.append(" (select u.id, u.user_name as userName from sys_user u where u.is_delete = 0 and u.corp_id = :corpId ");
		//sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		//sql.append(" on x.id = t.author ");
		sql.append(" LEFT JOIN (select y.id, y.post_id, y.last_reply_date, y.last_reply_user, y.view_count, y.reply_count from oa_forum_post_statistics y ");
		//sql.append(" left join (select u.id, u.user_name as userName from sys_user u where u.is_delete = 0 and u.corp_id = :corpId ");
		//sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) u1 on y.last_reply_user = u1.id  ");
		if(org.ezplatform.util.GlobalConstant.isQianBase()) {
			sql.append(" ) s on t.entityId = s.post_id limit 100");
		}else {
			sql.append(" ) s on t.entityId = s.post_id ");
		}
		sql.append(" ) a where 1 = 1 ");
		if(StringUtils.isNotEmpty(title)) {
			sql.append(" and a.title like '%"+title+"%'");
		}
		if("1".equals(type)) {
			if("1".equals(checkStatus)) {
				sql.append(" and a.checkStatus = "+ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
			}else if("0".equals(checkStatus)) {
				sql.append(" and a.checkStatus = "+ForumPost.CheckStatusEnum.CHECK_STATUS_CG.getValue());
			}else {
				sql.append(" and a.checkStatus <> "+ForumPost.CheckStatusEnum.CHECK_STATUS_CG.getValue());
			}
			
		}
		//起止时间查询
		if(StringUtils.isNotBlank(startTime)) {
			startTime = startTime + " 00:00:00";
			Date start = null;
			try {
				SimpleDateFormat  sdf1 =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				start = sdf1.parse(startTime);
			}catch(Exception e) {
				e.printStackTrace();
			}
			sql.append(" and a.publishTime >= :startTime ");
			values.put("startTime", start);
		}
		if(StringUtils.isNotBlank(endTime)) {
			endTime = endTime + " 23:59:59";
			Date end = null;
			try {
				SimpleDateFormat  sdf1 =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				end = sdf1.parse(endTime);
			}catch(Exception e) {
				e.printStackTrace();
			}
			sql.append(" and a.publishTime <= :endTime ");
			values.put("endTime", end);
		}
		values.put("corpId", corpId);
		values.put("author", userId);
		List<Integer> typeList = new ArrayList<>();
		if(StringUtils.equals(type, "2")) {
			typeList.add(POST_TYPE_REPLY);
			typeList.add(POST_TYPE_REPLY_COMMENTS);
			values.put("type", typeList);
		}else {
			values.put("type", StringUtils.isNotBlank(type) ? type : POST_TYPE_NEW);
		}
		
		String s = sql.toString();
		s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.publishTime desc,a.id", filter, pageable);
		Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
		List<String> bs = forumBoardService.getUserBoards();
		Iterator it = page.getContent().iterator();
		//我的帖子只需要查一次
		//每一条帖子的发帖人图像进行查询=====userId应为每个发帖人的userID,并非当前登录人的
		Map<String, String> map=getImage(userId,  corpId,  token);
		while (it.hasNext()) {
			Map m = (Map) it.next();
			//更改版块名称
			if(StringUtils.equals(m.get("boardIsDelete").toString(),"1")) {
				m.put("boardName", "-");
			}
			if(StringUtils.equals(m.get("boardStatus").toString(),"2")) {
				m.put("boardName", m.get("boardName"));
			}
			//类别被禁用,版块也被禁用
			if(StringUtils.equals(m.get("typeStatus").toString(),"2" )) {
				m.put("boardStatus", "2");
			}
			//获取用户角色权限
			boolean flag = false;
			if(user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
				flag = true;
			}
			m.put("isAdminRole", flag);
			boolean isModerator = false;
			if (!CollectionUtils.isEmpty(bs) && null != m) {
				if (bs.indexOf(m.get("boardId").toString()) >= 0) {
					isModerator = true;
				}
			}
			m.put("isModerator",isModerator);
			//黑名单标识(是管理员或者版主就不考虑)
			boolean blackListFlag = false;
			if(!flag && !isModerator) {
				String blackListStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_board_user_scope", "oa_forum_board", "id", StringUtils.null2String(m.get("boardId")));
				if(StringUtils.isNotEmpty(blackListStr)) {
					if(blackListStr.indexOf(user.getUserId()) != -1 || blackListStr.indexOf(user.getOrgId()) != -1) {
						blackListFlag = true;
					}
				}
			}
			m.put("blackListFlag",blackListFlag);
			m.putAll(map);
			//敏感词替换
			List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(corpId);
			List<String> sensitiveList = new ArrayList<String>();
			for (ForumSensitive forumSensitive : list) {
				sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
			}
			Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
			
			if(CollectionUtils.isNotEmpty(sensitiveList)) {
				m.put("title",SensitiveUtils.replaceSensitiveWord(initKeyWord, m.get("title").toString(), 2, "*"));
			}else {
				m.put("title",StringUtils.null2String(m.get("title")));
			}
			Object attIdJson;
			if (appType == "dingding") {
				attIdJson = transformAttachmentPlanform2Dd(StringUtils.null2String(m.get("attId")));
			} else {
				attIdJson = getAttachmentFile(m.get("attId"), token);
			}
			m.put("attIdJson", attIdJson);
		}
		return page;
	}
	
	
	/**
	 * 2.4版本:我的草稿下现在有四种状态的草稿;版块没被删除且没被禁用(1.草稿);版块被删没被禁用(1.草稿);版块没被删被禁用(1.草稿);版块被删被禁用(1.草稿)
	 * @param pageable
	 * @param filter
	 * @param token
	 * @param corpId
	 * @param type
	 * @param appType
	 * @param title
	 * @param checkStatus
	 * @return
	 */
	public Page<Map> mydraftList(Pageable pageable, List<PropertyFilter> filter, String token, String corpId,
			String type,String appType,String title, String checkStatus) {
		WebUser user = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		StringBuffer sql = new StringBuffer();
		Map<String, Object> values = new HashMap<String, Object>();
		sql.append(" select a.id, a.attId,a.content,a.title, a.boardId, a.author ,a.postId,a.isCollection, fn_date_format(a.createdDate,'MM-dd HH:mm') createdDate,fn_date_format(a.publishTime,'MM-dd HH:mm') publishTime, a.type, a.checkStatus, a.entityId, a.authorName ,a.typeName, a.boardName,a.boardIsdelete,a.boardStatus,a.isCheck, a.lastReplyUser, fn_date_format(a.lastReplyDate,'MM-dd HH:mm') lastReplyDate, a.view_count, a.reply_count,canSendPost,countSend ");
		sql.append(" from ( ");
		sql.append(" select t.id,t.attId,t.content, t.title, t.boardId, t.author,t.postId,t.isCollection, t.createdDate,t.publishTime, t.type, t.checkStatus, t.entityId, ");
		sql.append(" x.userName as authorName ,type.name as typeName, b.name as boardName,b.is_delete as boardIsdelete,b.status AS boardStatus,b.is_check as isCheck, s.last_reply_user as lastReplyUser, s.last_reply_date as lastReplyDate, s.view_count, s.reply_count,case when(obs.id is not null) then '1' ELSE '0' END AS canSendPost,oubs.countSend as countSend ");
		sql.append(" from ( ");
		sql.append(" select p.id,p.att_id attId,p.content,p.check_status as checkStatus,p.publish_time as publishTime");
		if("1".equals(type)) {
			sql.append(" ,case when ofs.id is null then 0 else 1 end as isCollection ");
		}else {
			sql.append(" ,p.is_collection as isCollection ");
		}
		sql.append(" , p.title, p.board_id as boardId, p.author, p.post_id as postId, p.createdDate, p.type, p.id as entityId ");
		sql.append(" from oa_forum_post p ");
		if("1".equals(type)) {
			sql.append(" left join oa_forum_scope ofs on ofs.fieldDataValue = p.is_collection and ofs.scopeValue = :author ");
		}
		
		sql.append(" where p.corp_id = :corpId and p.author = :author and p.is_delete = 0 and p.type in (:type) ");
		sql.append(" ) t ");
		sql.append(" inner join oa_forum_board b on t.boardId = b.id and b.status = 1 ");
		//sql.append(" and b.status = 1 ");
		sql.append(" inner join oa_forum_type type on b.forum_type = type.id and type.is_delete = 0  ");
		sql.append(" left join  ");
		sql.append(" (select u.id, u.user_name as userName from sys_user u where u.is_delete = 0 and u.corp_id = :corpId ");
		sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		sql.append(" on x.id = t.author ");
		sql.append(" LEFT JOIN (select y.id, y.post_id, y.last_reply_date, y.last_reply_user, y.view_count, y.reply_count, u1.userName as lastReplyUserName from oa_forum_post_statistics y left join ");
		sql.append(" (select u.id, u.user_name as userName from sys_user u where u.is_delete = 0 and u.corp_id = :corpId ");
		sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId)  ");
		sql.append(" u1 on y.last_reply_user = u1.id ) s on t.entityId = s.post_id ");
		//可发帖人
		sql.append(" LEFT JOIN (SELECT obs.id,obs.fieldDataValue FROM oa_forum_board_user_scope obs  WHERE obs.scopeValue = :author) obs ");
		sql.append("  ON t.boardid = obs.fieldDataValue  ");
		sql.append(" LEFT JOIN (SELECT count(oubs.fieldDataValue) as countSend,oubs.fieldDataValue FROM oa_forum_board_user_scope oubs group by oubs.fieldDataValue) oubs ");
		if(org.ezplatform.util.GlobalConstant.isQianBase()) {
			sql.append("  ON t.boardid = oubs.fieldDataValue limit 100");
		}else {
			sql.append("  ON t.boardid = oubs.fieldDataValue ");
		}
		sql.append(" ) a where 1 = 1 ");
		if(StringUtils.isNotEmpty(title)) {
			sql.append(" and a.title like '%"+title+"%'");
		}
		if("1".equals(type)) {
			if("1".equals(checkStatus)) {
				sql.append(" and a.checkStatus = "+ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
			}else if("0".equals(checkStatus)) {
				sql.append(" and a.checkStatus = "+ForumPost.CheckStatusEnum.CHECK_STATUS_CG.getValue());
			}else {
				sql.append(" and a.checkStatus <> "+ForumPost.CheckStatusEnum.CHECK_STATUS_CG.getValue());
			}
			
		}
		values.put("corpId", corpId);
		values.put("author", userId);
		List<Integer> typeList = new ArrayList<>();
		if(StringUtils.equals(type, "2")) {
			typeList.add(POST_TYPE_REPLY);
			typeList.add(POST_TYPE_REPLY_COMMENTS);
			values.put("type", typeList);
		}else {
			values.put("type", StringUtils.isNotBlank(type) ? type : POST_TYPE_NEW);
		}
		
		String s = sql.toString();
		s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.publishTime desc,a.id", filter, pageable);
		Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
		List<String> bs = forumBoardService.getUserBoards();
		Iterator it = page.getContent().iterator();
		//  我的帖子只需要查一次
		//每一条帖子的发帖人图像进行查询=====userId应为每个发帖人的userID,并非当前登录人的
		Map<String, String> map=getImage(userId,  corpId,  token);
		while (it.hasNext()) {
			Map m = (Map) it.next();
			if(StringUtils.equals(m.get("boardIsdelete").toString(), "1")) {
				m.put("boardId", "");
				m.put("boardName","-");
			}
			if(StringUtils.equals(m.get("boardStatus").toString(), "2")) {
				m.put("boardId", "");
				m.put("boardName",m.get("boardName"));
			}
			//获取用户角色权限
			boolean flag = false;
			if(user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
				flag = true;
			}
			m.put("isAdminRole", flag);
			boolean isModerator = false;
			if (!CollectionUtils.isEmpty(bs) && null != m) {
				if (bs.indexOf(m.get("boardId").toString()) >= 0) {
					isModerator = true;
				}
			}
			m.put("isModerator", isModerator);
			//黑名单标识(是管理员或者版主就不考虑)
			boolean blackListFlag = false;
			if(!flag && !isModerator) {
				String blackListStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_board_user_scope", "oa_forum_board", "id", StringUtils.null2String(m.get("boardId")));
				if(StringUtils.isNotEmpty(blackListStr)) {
					if(blackListStr.indexOf(user.getUserId()) != -1 || blackListStr.indexOf(user.getOrgId()) != -1) {
						blackListFlag = true;
					}
				}
			}
			m.put("blackListFlag",blackListFlag);
			m.putAll(map);
			//敏感词替换
			List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(corpId);
			List<String> sensitiveList = new ArrayList<String>();
			for (ForumSensitive forumSensitive : list) {
				sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
			}
			Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
			
			if(CollectionUtils.isNotEmpty(sensitiveList)) {
				m.put("title",SensitiveUtils.replaceSensitiveWord(initKeyWord, m.get("title").toString(), 2, "*"));
			}else {
				m.put("title",StringUtils.null2String(m.get("title")));
			}
//			if(sList!=null&&sList.size()>0) {
//				m.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, m.get("title").toString(), 2, "*"));
//			}
			Object attIdJson;
			if (appType == "dingding") {
				attIdJson = transformAttachmentPlanform2Dd(StringUtils.null2String(m.get("attId")));
			} else {
				attIdJson = getAttachmentFile(m.get("attId"), token);
			}
			m.put("attIdJson", attIdJson);
		}
		return page;
	}
	
	/**
	 * @param page
	 * @param pageSize
	 * @param corpId
	 * @param boardId
	 * @param type 
	 * @return
	 * @Title: allPostList
	 * @Description: 所以帖子列表页面(优化查询)
	 * @return: Page<Map>
	 * @date 2017年11月25日 下午12:54:58
	 */
	@SuppressWarnings("rawtypes")
	public List<Map> allPostListDing(String page, String pageSize, String token, String corpId,
			String boardId, String activeTabIndex, String treeType, String title, String type, String startDate, String endDate) {
		int pageSizeInt = Integer.parseInt(pageSize);
		int start = (Integer.parseInt(page)-1)*pageSizeInt;
		WebUser user = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT t.id AS boardId,t.aplication_scope,t.forumType,p.publist_type AS publishType,p.is_essence AS isEssence,t.NAME AS boardName,");
		sql.append(" p.id,p.author,p.title,	p.createdDate,p.top_date,p.type,CASE WHEN ofs.id IS NULL THEN 0 ELSE 1 END AS isCollection,p.is_top,p.att_id as attId, ");
		sql.append(" p.is_anonymity AS isAnonymity,p.is_petname AS isPetname,p.petname,p.publish_time AS publishTime, ");
		sql.append(" ps.last_reply_date AS lastReplyDate,ps.last_reply_user AS lastReplyUser,ps.last_reply_id as lastReplyPostId,");
		sql.append(" ps.view_count AS viewCount,ps.reply_count AS replyCount ");
		if(StringUtils.isNotEmpty(title)) {
			sql.append(" ,authorName ");
		}
		sql.append(" from oa_forum_post p ");
		sql.append(" inner JOIN  ");
		sql.append(" (select DISTINCT b.id, b.name ,b.is_anonymity ,b.aplication_scope,type1.name AS forumType ");
		sql.append(" from oa_forum_board b ");
		sql.append(" inner join oa_forum_type type1 on b.forum_type = type1.id and type1.is_delete = 0 and type1.status = 1 ");
		sql.append(" where b.status = '1' and b.corp_id = :corpId and b.is_delete = 0 ) t on p.board_id = t.id ");
		sql.append(" left join oa_forum_scope ofs on ofs.fieldDataValue = p.is_collection and ofs.scopeValue = :userId ");
		sql.append(" left join oa_forum_post_statistics ps on p.id = ps.post_id ");
		if (StringUtils.isNotEmpty(title)) {
			sql.append(" left join  ");
			sql.append(" (select u.id as userId, u.user_name as authorName from sys_user u where u.corp_id = :corpId ");
			sql.append(" union select a.id, a.trueName as authorName from sys_admin a where a.corp_id = :corpId) x ");
			sql.append(" on x.userId = p.author ");
		}
		sql.append(" where p.corp_id = :corpId and p.type = '1' and p.is_delete = 0 ");
		if("2".equals(activeTabIndex)) {//精华帖子
			sql.append(" and p.is_essence = '1' ");
		}
		if("3".equals(activeTabIndex)) {//公告帖子
			sql.append(" and p.publist_type = '2' ");
		}
		if(StringUtils.isNotBlank(boardId) && "1".equals(treeType)) {
			sql.append(" and p.board_id in ( select b.id from oa_forum_board b, oa_forum_type x where b.forum_type = x.id  ");
			sql.append("  and b.status = 1 and b.is_delete = 0 and b.corp_id = :corpId  and x.is_delete = 0   ");
			sql.append("  and x.status = 1 and x.corp_id = :corpId and b.forum_type= :boardId )");
		}else if (StringUtils.isNotBlank(boardId) ) {
			sql.append(" and p.board_id = :boardId ");
		}
		sql.append(" and (p.check_status ="+ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue()+" or p.check_status ="+ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue()+")");
		//首页-搜索搜贴,找人,搜版块;版块导航-搜贴,找人
		if(StringUtils.isNotEmpty(title)) {
			title = SqlUtils.escapeNormalChars(title);
			if("1".equals(type)) {
				if(StringUtils.equals(title, "匿名")) {
					sql.append(" and (title like '%"+title+"%' or (( authorName like '%"+title+"%')  or  (author <> :userId and p.is_anonymity = 1)))");
				}else {
					sql.append(" and (title like '%"+title+"%' or ( authorName like '%"+title+"%' and p.is_petname <> 1  ) or (p.petname like '%"+title+"%')  and  (p.is_anonymity <> 1 or (author = :userId and p.is_anonymity = 1)  or (author = :userId and p.is_petname = 1)))");
				}
			}else {
				if(StringUtils.equals(title, "匿名")) {
					sql.append(" and (title like '%"+title+"%' or t.NAME like '%"+title+"%' or(( authorName like '%"+title+"%')  or  (author <> :userId and p.is_anonymity = 1)))");
				}else {
					sql.append(" and (title like '%"+title+"%' or t.NAME like '%"+title+"%' or( authorName like '%"+title+"%' and p.is_petname <> 1)  or (p.petname like '%"+title+"%')  and  (p.is_anonymity <> 1 or (author = :userId and p.is_anonymity = 1) or (author = :userId and p.is_petname = 1)))");
				}
			}
		}
		//起止时间查询
		if(StringUtils.isNotBlank(startDate)) {
			Date star = null;
			try {
				SimpleDateFormat  sdf1 =  new SimpleDateFormat("yyyy-MM-dd");
				star = sdf1.parse(startDate);
			}catch(Exception e) {
				e.printStackTrace();
			}
			sql.append(" and p.publish_time >= :startTime ");
			paramMap.put("startTime", star);
		}
		if(StringUtils.isNotBlank(endDate)) {
			//给结束日期加一天
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String result = "";
			try {
				Date dt = df.parse(endDate);
				result = df.format(DateUtils.addDays(dt, 1));
			} catch (Exception e) {
				e.printStackTrace();
			}
			Date end = null;
			try {
				SimpleDateFormat  sdf2 =  new SimpleDateFormat("yyyy-MM-dd");
				end = sdf2.parse(result);
			}catch(Exception e) {
				e.printStackTrace();
			}
			sql.append(" and p.publish_time <= :endTime ");
			paramMap.put("endTime", end);
		}
		//适用范围sql匹配
		String scopeSql = cmpApplyScopeService.getInScopeDataSql(userId, "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",paramMap);
		sql.append(" and " + scopeSql);
		if("1".equals(type)) {
			if("1".equals(activeTabIndex)){//最热
				sql.append(" ORDER BY is_top desc, top_date desc, viewCount desc,publishTime desc,id desc");
			}else if("0".equals(activeTabIndex)){//最新
				sql.append(" ORDER BY is_top desc, top_date desc, publishTime desc,id desc");
			}else if("2".equals(activeTabIndex)) {//精华
				sql.append(" ORDER BY is_top desc, top_date desc, publishTime desc,id desc");
			} else{
				sql.append(" ORDER BY is_top desc,top_date desc,publishTime desc,id desc");
			}
		}else {
			if("1".equals(activeTabIndex)){//最热
				sql.append(" ORDER BY viewCount desc,replyCount desc,id desc");
			}else if("0".equals(activeTabIndex)){//最新
				sql.append(" ORDER BY publishTime desc,id desc");
			}else if("2".equals(activeTabIndex)) {//精华
				sql.append(" ORDER BY is_top desc,top_date desc,publishTime desc,id desc");
			} else{
				sql.append(" ORDER BY is_top desc,top_date desc,publishTime desc,id desc");
			}
		}
		paramMap.put("corpId", corpId);
		paramMap.put("userId", userId);
		if (StringUtils.isNotBlank(boardId) ) {
			paramMap.put("boardId", boardId);
		}
		List<Map> r = super.findByListNativeQuery(sql.toString(), null, paramMap, start, pageSizeInt);
		Iterator i = r.iterator();
		List<String> l = new ArrayList<String>();
		List<String> authors = new ArrayList<String>();
		//获取敏感词
//		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(corpId);
//		List<String> sensitiveList = new ArrayList<String>();
//		for (ForumSensitive forumSensitive : list) {
//			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
//		}
//		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		//获取用户角色权限
		boolean flag = false;
		if(user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
			flag = true;
		}
		while (i.hasNext()) {
			Map a = (Map) i.next();
			a.put("isAdminRole", flag);
			l.add(a.get("id").toString());
			authors.add(StringUtils.null2String(a.get("author")));
			// 对每一条帖子信息的附件信息进行查询
			String attId = StringUtils.null2String(a.get("attId"));
			int imageNum = 0;
			if(attId !=null&&StringUtils.isNotBlank(attId)) {
				imageNum =  attId.split("\\|").length;
			}
			a.put("imageNum", imageNum);
			a.put("attIdJson", transformAttachmentPlanform2Dd(attId));
			//每一条帖子的发帖人图像进行查询=====userId应为每个发帖人的userID,并非当前登录人的
			String author=StringUtils.null2String(a.get("author"));
			String isAnonymity=StringUtils.null2String(a.get("isAnonymity"));//如果是匿名就不去查了 1 匿名  0  实名
			if("1".equals(isAnonymity)&&!author.equals(userId)) {
				a.put("authorName", "匿名");
			}else {
				a.put("authorName", cmpPopUserOrgName.getUserNameById(author));
			}
			
			//敏感词替换
//			if(sensitiveList!=null&&sensitiveList.size()>0) {
//				a.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, a.get("title").toString(), 2, "*"));
//			}
			a.put("title", a.get("title").toString());
			Map<String, String> map=new HashMap<>();
			if("0".equals(isAnonymity)) {
			map=getImage(author,  corpId,  token);
			}else {
				map.put("fileName", "");
				map.put("image", "");
			}
			a.putAll(map);
		}
		// 获取到所有的标签
		List<Map> allLabel = forumLabelService.findAllLabel(corpId);
		List<Map> r1 = null;
		if (l.size() > 0) {
			String sql2 = "select pl.post_id as postId, l.id from oa_forum_post_label pl INNER join oa_forum_label l on l.id = pl.label_id where pl.post_id in (:l) and l.is_delete = 0 order by postId, sort_no, createdDate desc, name desc ";
			Map<String, Object> paramMap2 = new HashMap<String, Object>();
			paramMap2.put("l", l);
			r1 = super.findByListNativeQuery(sql2.toString(), null, paramMap2);
		}
		for (Map p : r) {
			// 匹配帖子标签start
			if (l.size() > 0) {
				String pid = StringUtils.null2String(p.get("id"));
				List<Map> lables = new ArrayList();
				for (Map sl : allLabel) {
					Boolean f = false;
					if (!CollectionUtils.isEmpty(r1)) {
						for (Map map : r1) {
							if (StringUtils.equals(sl.get("id").toString(), StringUtils.null2String(map.get("id")))
									&& StringUtils.equals(pid, StringUtils.null2String(map.get("postId")))) {
								f = true;
							}
						}
					}
					Map swapm = new HashMap();
					swapm.put("id", sl.get("id"));
					swapm.put("name", sl.get("name"));
					swapm.put("color", sl.get("color"));
					swapm.put("status", sl.get("status"));
					if (f) {
						swapm.put("checked", true);
					} else {
						swapm.put("checked", false);
					}
					lables.add(swapm);
				}
				p.put("labels", lables);
			}
		}
		return r;
	}
	
	/**
	 * @param pageable
	 * @param filter
	 * @param corpId
	 * @param boardId
	 * @param forumType 
	 * @param searchContent 
	 * @param searchType 
	 * @return
	 * @Title: allPostList
	 * @Description: 所以帖子列表页面
	 * @return: Page<Map>
	 * @date 2017年11月25日 下午12:54:58
	 */
	@SuppressWarnings("rawtypes")
	public Page<Map> allPostList(Pageable pageable, List<PropertyFilter> filter, String token, String corpId,
		    String boardId, String appType,String pId,String activeTabIndex,String treeType,String title, String forumType, String searchContent, String searchType) {
		WebUser user = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		StringBuffer sql = new StringBuffer();
		if(pId==null || "null".equals(pId)) {
			pId="";
		}
		//如果是钉钉来的   就不区分一级版主了
		if("dingding".equals(appType)) {
			pId="dingding";
		}
		Map<String, Object> values = new HashMap<String, Object>();
		sql.append(" SELECT id,publishType,isEssence,author,boardId,boardName,title,fn_date_format(createdTime,'MM-dd HH:mm') createdDate,fn_date_format(topTime,'MM-dd HH:mm') top_date,type,is_top,isAnonymity,isPetname,petname,attId, ");
		sql.append(" fn_date_format(lastReplyTime,'yyyy-MM-dd HH:mm') lastReplyDate,lastReplyUser,lastIsAnonymity,lastIsPetname,lastreplyPetname,isCopy,isRePost,isEditPost,viewCount,replyCount,isModerator,isCollection,publishTime ");
		if (StringUtils.isNotEmpty(searchContent)) {
			if (StringUtils.equals(searchType, "1") || StringUtils.equals(searchType, "0")) {
				sql.append(" ,authorName ");
			}
        }
		sql.append(" FROM ( select a.id,a.publishType,a.isEssence,a.boardName, a.boardid as boardId ,a.author, a.title,a.checkStatus ");
		//排序的时候createdDate需要年，展示的时候不需要年，所以oracle会报错，所以单独的将createdDate和top_date的数据拿出来 
		sql.append(" ,a.createdDate as createdTime,a.lastReplyDate as lastReplyTime,a.top_date as topTime,a.isCollection,fn_date_format(a.createdDate,'yyyy-MM-dd HH:mm:ss') createdDate,fn_date_format(a.top_date,'yyyy-MM-dd HH:mm:ss') top_date,  ");
		sql.append("  a.type, a.is_top,a.isCopy,a.isRePost,a.isEditPost, a.isAnonymity,a.isPetname,a.petname, a.attId, fn_date_format(a.lastReplyDate,'yyyy-MM-dd HH:mm') lastReplyDate, a.lastReplyUser,  ");
		//sql.append(" CASE  WHEN (os.scopeValue = :userId or a.lastReplyUser = :userId or a.is_anonymity = 0) ");
		//sql.append(" CASE  WHEN (a.is_anonymity = 1) ");
		//sql.append(" THEN '匿名' WHEN (a.lastIsPetname = 1) THEN a.lastreplyPetname ELSE a.lastReplyUserName END AS lastReplyUserName,");
		sql.append("  lastIsAnonymity,lastIsPetname,lastreplyPetname,a.viewCount, a.replyCount, a.isModerator,a.publishTime from ( ");
		sql.append(" select t.id AS boardid,p.publist_type AS publishType,p.is_essence AS isEssence,t.name as boardName, p.id, p.author, p.title,p.check_status as checkStatus, p.createdDate, p.top_date, p.type,case when ofs.id is null then 0 else 1 end as isCollection, p.is_top, p.is_anonymity as isAnonymity,p.is_petname as isPetname,p.petname, p.att_id as attId, ");
		sql.append(" ps.last_reply_date as lastReplyDate,");
		sql.append(" p.is_copy as isCopy,p.is_re_post as isRePost,p.is_edit_post as isEditPost, ps.last_reply_user as lastReplyUser,ps.is_anonymity as lastIsAnonymity,ps.is_petname as lastIsPetname,ps.lastpetname as lastreplyPetname, ps.view_count as viewCount, ps.reply_count as replyCount,t.is_anonymity as boardIsAnonymity, t.isModerator,p.publish_time as publishTime  ");
		sql.append(" from oa_forum_post p ");
		sql.append(" inner JOIN  ");
		sql.append(" (select DISTINCT b.id, b.name ,b.is_anonymity , case when :userName = 'admin' then 1 WHEN s.id is not null then 1  else 0 end isModerator ");
		sql.append(" from oa_forum_board b ");
		sql.append(" inner join oa_forum_type type on b.forum_type = type.id and type.is_delete = 0 and type.status = 1 ");
		sql.append(" LEFT JOIN oa_forum_moderator_scope s on b.id = s.fieldDataValue and s.fieldDataTable = 'oa_forum_board' and s.scopeType = 'user' and s.scopeValue = :userId ");
		sql.append(" where b.status = '1' and b.corp_id = :corpId and b.is_delete = 0 ) t on p.board_id = t.id ");
		sql.append(" left join oa_forum_scope ofs on ofs.fieldDataValue = p.is_collection and ofs.scopeValue = :userId ");
		sql.append(" LEFT JOIN (select y.id, y.post_id, y.last_reply_date, y.last_reply_user, y.view_count, y.reply_count,");
		// 判断是否显示匿名
		sql.append(" aa.is_anonymity,aa.is_petname,aa.petname as lastpetname ");
		sql.append(" from oa_forum_post_statistics y  ");
		/*sql.append(" ( left join select u.id, u.user_name as userName from sys_user u where u.corp_id = :corpId ");
		sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId)  ");
		sql.append(" u1 on y.last_reply_user = u1.id ");*/
		sql.append(" left join oa_forum_post aa on aa.id = y.last_reply_id and aa.corp_id = :corpId ) ");
		sql.append(" ps on p.id = ps.post_id ");
		/*sql.append(" left join  ");
		sql.append(" (select u.id, u.user_name as userName from sys_user u where u.corp_id = :corpId ");
		sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		sql.append(" on x.id = p.author ");*/
		sql.append(" where p.corp_id = :corpId and p.type = '1' and p.is_delete = 0 ");
		//精华页签(isEssence==1)
		if("3".equals(forumType)) {
			sql.append(" and p.is_essence = '1' ");
		}
		//公告页签(forumType==4)
		if("4".equals(forumType)) {
			sql.append(" and p.publist_type = 2 ");
		}
		if(StringUtils.isNotBlank(boardId) && "2".equals(treeType)) {
			sql.append(" and p.board_id in ( select b.id from oa_forum_board b, oa_forum_type x where b.forum_type = x.id  ");
			sql.append(" and b.status = 1 and b.is_delete = 0 and b.corp_id = :corpId  and x.is_delete = 0   ");
			sql.append(" and x.status = 1 and x.corp_id = :corpId and b.forum_type= :boardId )");
			values.put("corpId", corpId);
			values.put("boardId", boardId);
		}else if (StringUtils.isNotBlank(boardId) ) {
			sql.append(" and p.board_id = :boardId ");
			values.put("boardId", boardId);
		}
		sql.append(" and (p.check_status ="+ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue()+" or p.check_status ="+ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue()+")");
		if(org.ezplatform.util.GlobalConstant.isQianBase()) {
			sql.append(") a limit 10");
		}else {
			sql.append(") a ");
		}
		//sql.append(") a LEFT JOIN (SELECT os.scopeValue,os.fieldDataValue FROM oa_forum_moderator_scope os  WHERE os.scopeValue = :userId) os ");
		/*sql.append("  ON a.boardid = os.fieldDataValue  ");
		//可发帖人
		sql.append(" LEFT JOIN (SELECT obs.id,obs.fieldDataValue FROM oa_forum_board_user_scope obs  WHERE obs.scopeValue = :userId) obs ");
		sql.append(" ON a.boardid = obs.fieldDataValue  ");
		sql.append(" LEFT JOIN (SELECT count(oubs.fieldDataValue) as countSend,oubs.fieldDataValue FROM oa_forum_board_user_scope oubs group by oubs.fieldDataValue) oubs ");
		sql.append(" ON a.boardid = oubs.fieldDataValue  ");*/
		sql.append(" ) a ");
		if (StringUtils.isNotEmpty(searchContent)) {
			if (StringUtils.equals(searchType, "1") || StringUtils.equals(searchType, "0")) {
				sql.append(" left join  ");
				sql.append(" (select u.id as userId, u.user_name as authorName from sys_user u where u.corp_id = :corpId ");
				sql.append(" union select a.id, a.trueName as authorName from sys_admin a where a.corp_id = :corpId) x ");
				sql.append(" on x.userId = a.author ");
			}
			searchContent = SqlUtils.escapeNormalChars( searchContent );
        }
		sql.append(" where 1 = 1 ");
		if("1".equals(searchType)) {
			if(StringUtils.isNotEmpty(searchContent)) {
				if(StringUtils.equals(searchContent, "匿名")) {
					sql.append(" and  (authorName like '%"+searchContent+"%' ");
					sql.append(" or  (a.author <> :userId and a.isAnonymity = 1)) ");
				}else {
					sql.append(" and  ((authorName like '%"+searchContent+"%' and a.isPetname <> 1) or (a.petname like '%"+searchContent+"%' )) ");
					sql.append(" and  (a.isAnonymity <> 1 or (a.author = :userId and a.isAnonymity = 1) or (a.author = :userId and a.isPetname = 1)) ");
				}
			}
		}else if("2".equals(searchType)){
			if(StringUtils.isNotEmpty(searchContent)) {
				sql.append(" and a.title like '%"+searchContent+"%' ");
			}
		}else if("0".equals(searchType)) {
			if(StringUtils.isNotEmpty(searchContent)) {
				if(StringUtils.equals(searchContent, "匿名")) {
					sql.append(" and (a.title like '%"+searchContent+"%' or(( authorName like '%"+searchContent+"%')  or  (a.author <> :userId and a.isAnonymity = 1)))");
				}else {
					sql.append(" and (a.title like '%"+searchContent+"%' or ( (authorName like '%"+searchContent+"%' and a.isPetname <> 1 ) or (a.petname like '%"+searchContent+"%' ))  and  (a.isAnonymity <> 1 or (a.author = :userId and a.isAnonymity = 1)  or (a.author = :userId and a.isPetname = 1)))");
				}
			}
		}
		values.put("userId", userId);
		values.put("corpId", corpId);
		values.put("userName", user.getUserName());
		String s = sql.toString();
		if("0".equals(activeTabIndex)) {//最新
			s = PropertyFilter.getSqlByFilterAndPageable("a", s, " a.is_top desc,a.publishTime desc,a.id", filter, pageable);
		}else if("1".equals(activeTabIndex)){
			s = PropertyFilter.getSqlByFilterAndPageable("a", s, " a.is_top desc,a.replyCount desc, a.viewCount desc,a.id", filter, pageable);
		}else {//pc端不受影响
			if("1".equals(forumType)) {//最新
				s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.is_top desc, a.top_date desc, a.publishTime desc,a.id", filter, pageable);
			}else if("2".equals(forumType)) {//热门
				s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.is_top desc, a.top_date desc, a.viewCount desc,a.publishTime desc,a.id", filter, pageable);
			}else if("3".equals(forumType)) {//精华
				s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.is_top desc, a.top_date desc, a.publishTime desc,a.id", filter, pageable);
			}else if("4".equals(forumType)) {//公告
				s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.is_top desc, a.top_date desc,a.publishTime desc,a.id", filter, pageable);
			}
			
		}
		// 获取到所有的标签
		List<Map> allLabel = forumLabelService.findAllLabels(corpId);
		Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
		List<Map> m = page.getContent();
		Iterator i = m.iterator();
		List<String> l = new ArrayList<String>();
		List<String> authors = new ArrayList<String>();
//		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(corpId);
//		List<String> sensitiveList = new ArrayList<String>();
//		for (ForumSensitive forumSensitive : list) {
//			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
//		}
//		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		//获取用户角色权限
		boolean flag = false;
		if(StringUtils.isNotEmpty(user.getRoleCodes()) && (user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user))) {
			flag = true;
		}
		
		while (i.hasNext()) {
			Map a = (Map) i.next();
			a.put("isAdminRole", flag);
			a.put("authorName", cmpPopUserOrgName.getUserNameById(StringUtils.null2String(a.get("author"))));
			a.put("lastReplyUserName", cmpPopUserOrgName.getUserNameById(StringUtils.null2String(a.get("lastReplyUser"))));
			/*if(a.get("createddate") != null) {//解决查询时常出现大写字母变小写的问题
				a.put("createdDate", a.get("createddate"));
				a.put("boardName", a.get("boardname"));
				a.put("boardId", a.get("boardid"));
				a.put("authorName", cmpPopUserOrgName.getUserNameById(StringUtils.null2String(a.get("author"))));
				a.put("isAnonymity", a.get("isAnonymity"));
				a.put("attId", a.get("attid"));
				a.put("lastReplyDate", a.get("lastReplyDate"));
				a.put("lastReplyUser", a.get("lastReplyUser"));
				a.put("lastReplyUserName", cmpPopUserOrgName.getUserNameById(StringUtils.null2String(a.get("lastReplyUser"))));
				a.put("viewCount", a.get("viewcount"));
				a.put("replyCount", a.get("replycount"));
				a.put("isModerator", a.get("ismoderator"));
			}*/
			//黑名单标识(是管理员或者版主就不考虑)
			/*boolean blackListFlag = false;
			if(!flag || !StringUtils.equals(a.get("isModerator").toString(), "1")) {
				String blackListStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_board_user_scope", "oa_forum_board", "id", StringUtils.null2String(a.get("boardId")));
				if(StringUtils.isNotEmpty(blackListStr)) {
					if(blackListStr.indexOf(user.getUserId()) != -1 || blackListStr.indexOf(user.getOrgId()) != -1) {
						blackListFlag = true;
					}
				}
			}
			a.put("blackListFlag", blackListFlag);*/
			l.add(a.get("id").toString());
			authors.add(StringUtils.null2String(a.get("author")));
			// 对每一条帖子信息的附件信息进行查询
			/*String attId = StringUtils.null2String(a.get("attId"));
			Object attIdJson;
			if (StringUtils.equals(appType, "dingding")) {
				attIdJson = transformAttachmentPlanform2Dd(attId);
			} else {
				attIdJson = getAttachmentFile(attId, token);
			}
			a.put("attIdJson", attIdJson);*/
			//每一条帖子的发帖人图像进行查询=====userId应为每个发帖人的userID,并非当前登录人的
			String author=StringUtils.null2String(a.get("author"));
			if(author.equals(userId)){
				a.put("isauthor", 1);
			}else{
				a.put("isauthor", 0);
			}
			//敏感词替换
			List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(corpId);
			List<String> sensitiveList = new ArrayList<String>();
			for (ForumSensitive forumSensitive : list) {
				sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
			}
			Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
			
			if(CollectionUtils.isNotEmpty(sensitiveList)) {
				a.put("title",SensitiveUtils.replaceSensitiveWord(initKeyWord, a.get("title").toString(), 2, "*"));
			}else {
				a.put("title",StringUtils.null2String(a.get("title")));
			}
//			if(sensitiveList!=null&&sensitiveList.size()>0) {
//				a.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, a.get("title").toString(), 2, "*"));
//			}
			/*String isAnonymity=StringUtils.null2String(a.get("isAnonymity"));//如果是匿名就不去查了 1 匿名  0  实名
			if("1".equals(isAnonymity)&&!author.equals(userId)) {
				a.put("authorName", "匿名");
			}
			//Map<String, String> map=new HashMap<>();
			if("0".equals(isAnonymity)) {
			map=getImage(author,  corpId,  token);
			}else {
				map.put("fileName", "");
				map.put("image", "");
			}
			a.putAll(map);*/
		}
		
		List<Map> r1 = null;
		if (l.size() > 0) {
			String sql2 = "select pl.post_id as postId, l.id from oa_forum_post_label pl INNER join oa_forum_label l on l.id = pl.label_id where pl.post_id in (:l) and l.is_delete = 0 order by postId, sort_no, createdDate desc, name desc";
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("l",l);
			r1 = super.findByListNativeQuery(sql2.toString(), null, paramMap);
		}
		for (Map p : m) {
			// 匹配帖子标签start
			if (l.size() > 0) {
				String pid = StringUtils.null2String(p.get("id"));
				List<Map> lables = new ArrayList();
				for (Map sl : allLabel) {
					Boolean f = false;
					if (!CollectionUtils.isEmpty(r1)) {
						for (Map map : r1) {
							if (StringUtils.equals(sl.get("id").toString(), StringUtils.null2String(map.get("id")))
									&& StringUtils.equals(pid, StringUtils.null2String(map.get("postId")))) {
								f = true;
							}
						}
					}
					Map swapm = new HashMap();
					swapm.put("id", sl.get("id"));
					swapm.put("name", sl.get("name"));
					swapm.put("color", sl.get("color"));
					swapm.put("status", sl.get("status"));
					if (f) {
						swapm.put("checked", true);
					} else {
						swapm.put("checked", false);
					}
					lables.add(swapm);
				}
				p.put("labels", lables);
			}
		}
		return page;
	}
	
	/**
	 * 所有帖子菜单查询(优化查询)
	 * @param title
	 * @param publishType
	 * @param typeId
	 * @param boardId
	 * @param author
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public Page<Map> searchAllPost(String title,String publishType,String typeId,String boardId,
			String author,String startTime,String endTime,WebUser user,Pageable pageable,String tab,String searchType,List<PropertyFilter> filter,String mdpostType){
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		StringBuffer sql = new StringBuffer();
		Map<String, Object> values = new HashMap<String, Object>();
		sql.append(" SELECT t.id AS boardId,t.aplication_scope,t.forumType,p.publist_type AS publishType,p.is_essence AS isEssence,t.NAME AS boardName,");
		sql.append(" p.id,p.author,p.title,	p.createdDate,p.top_date,p.type,CASE WHEN ofs.id IS NULL THEN 0 ELSE 1 END AS isCollection,p.is_top,p.att_id as attId, ");
		sql.append(" p.is_anonymity AS isAnonymity,p.is_petname AS isPetname,p.petname,p.publish_time AS publishTime, ");
		sql.append(" ps.last_reply_date AS lastReplyDate,ps.last_reply_user AS lastReplyUser,ps.last_reply_id as lastReplyPostId,");
		//sql.append(" ps.is_anonymity as replyisanonymity,ps.is_petname as replyispetname,ps.replypetname,");
		sql.append(" ps.view_count AS viewCount,ps.reply_count AS replyCount ");
		if(StringUtils.isNotEmpty(author) || StringUtils.equals(searchType, "2")) {
			sql.append(" ,authorName ");
		}
		sql.append(" from oa_forum_post p ");
		sql.append(" inner JOIN  ");
		sql.append(" (select DISTINCT b.id, b.name ,b.is_anonymity ,b.aplication_scope,type1.name AS forumType ");
		sql.append(" from oa_forum_board b ");
		sql.append(" inner join oa_forum_type type1 on b.forum_type = type1.id and type1.is_delete = 0 and type1.status = 1 ");
		sql.append(" where b.status = '1' and b.corp_id = :corpId and b.is_delete = 0 ) t on p.board_id = t.id ");
		sql.append(" left join oa_forum_scope ofs on ofs.fieldDataValue = p.is_collection and ofs.scopeValue = :userId ");
		sql.append(" left join oa_forum_post_statistics ps on p.id = ps.post_id ");
		/*sql.append(" LEFT JOIN (select y.id, y.post_id, y.last_reply_date, y.last_reply_user, y.view_count, y.reply_count,");
		sql.append(" aa.is_anonymity,aa.is_petname,aa.petname as replypetname ");
		sql.append(" from oa_forum_post_statistics y ");
		sql.append(" left join oa_forum_post aa on aa.id = y.last_reply_id and aa.corp_id = :corpId ) ");
		sql.append(" ps on p.id = ps.post_id ");*/
		if (StringUtils.isNotEmpty(author) || StringUtils.equals(searchType, "2")) {
			sql.append(" left join  ");
			sql.append(" (select u.id as userId, u.user_name as authorName from sys_user u where u.corp_id = :corpId ");
			sql.append(" union select a.id, a.trueName as authorName from sys_admin a where a.corp_id = :corpId) x ");
			sql.append(" on x.userId = p.author ");
		}
		sql.append(" where p.corp_id = :corpId and p.type = '1' and p.is_delete = 0 ");
		//精华页签(isEssence==1)
		if("3".equals(tab)) {
			sql.append(" and p.is_essence = '1' ");
		}
		if(StringUtils.isNotBlank(typeId)) {
			sql.append(" and p.board_id in ( select b.id from oa_forum_board b, oa_forum_type x where b.forum_type = x.id  ");
			sql.append(" and b.status = 1 and b.is_delete = 0 and b.corp_id = :corpId  and x.is_delete = 0   ");
			sql.append(" and x.status = 1 and x.corp_id = :corpId and b.forum_type= :typeId )");
			values.put("corpId", corpId);
			values.put("typeId", typeId);
		}
		if (StringUtils.isNotBlank(boardId) ) {
			sql.append(" and p.board_id = :boardId ");
			values.put("boardId", boardId);
		}
		sql.append(" and (p.check_status ="+ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue()+" or p.check_status ="+ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue()+")");
		if("1".equals(mdpostType)) {
			//适用版主sql匹配
			sql.append(" and (p.board_id in ( select fieldDataValue from oa_forum_moderator_scope where  fieldData='id' and fieldDataTable='oa_forum_board' and scopeValue in  (:userId))) " );
			values.put("userId", user.getUserId());
		}
		//评论页签不显示无回复帖子
		if("4".equals(tab)) {
			sql.append(" and ps.reply_count > 0 ");
		}
		//发布类型查询
		if(StringUtils.isNotBlank(publishType)) {
			sql.append("and p.publist_type = :publishType");
			values.put("publishType", publishType);
		}
		//点击版块导航的搜索框还是点击高级搜索再进行搜索
		if(StringUtils.equals(searchType, "2")) {
			title = SqlUtils.escapeNormalChars(title);
			author = SqlUtils.escapeNormalChars(author);
			if(StringUtils.equals(title, "匿名")) {
				sql.append(" and (title like '%"+title+"%' or (( authorName like '%"+author+"%')  or  (author <> :userId and p.is_anonymity = 1)))");
			}else {
				sql.append(" and (title like '%"+title+"%' or ( authorName like '%"+author+"%' and p.is_petname <> 1 ) or (p.petname like '%"+author+"%') and  (p.is_anonymity <> 1 or (author = :userId and p.is_anonymity = 1) or (author = :userId and p.is_petname = 1)))");
			}
		}else {
			//作者模糊查询
			if (StringUtils.isNotEmpty(author)) {
				author = SqlUtils.escapeNormalChars(author);
				if(StringUtils.equals(author, "匿名")) {
					sql.append(" and  (authorName like '%"+author+"%' ");
					sql.append(" or  (author <> :userId and p.is_anonymity = 1)) ");
				}else {
					sql.append(" and  ((authorName like '%"+author+"%' and p.is_petname <> 1 ) or (p.petname like '%"+author+"%'))");
					sql.append(" and  (p.is_anonymity <> 1 or (author = :userId and p.is_anonymity = 1)  or (author = :userId and p.is_petname = 1)) ");
				}
	        }
			//标题模糊查询
			if(StringUtils.isNotEmpty(title)) {
				sql.append(" and title like '%"+title+"%' ");
			}
		}
		//起止时间查询
		if(StringUtils.isNotBlank(startTime)) {
			startTime = startTime + " 00:00:00";
			Date start = null;
			try {
				SimpleDateFormat  sdf1 =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				start = sdf1.parse(startTime);
			}catch(Exception e) {
				e.printStackTrace();
			}
			sql.append(" and p.publish_time >= :startTime ");
			values.put("startTime", start);
		}
		if(StringUtils.isNotBlank(endTime)) {
			endTime = endTime + " 23:59:59";
			Date end = null;
			try {
				SimpleDateFormat  sdf2 =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				end = sdf2.parse(endTime);
			}catch(Exception e) {
				e.printStackTrace();
			}
			sql.append(" and p.publish_time <= :endTime ");
			values.put("endTime", end);
		}
		values.put("userId", userId);
		values.put("corpId", corpId);
		String s = sql.toString();
		//适用范围sql匹配
		//String scopeSql = cmpApplyScopeService.getInScopeDataSql(userId, "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",values);
		//System.out.println("scopeSql:"+scopeSql);
		//s+= " and " + scopeSql;
		if("1".equals(tab)) {//最新
			s = PropertyFilter.getSqlByFilterAndPageable("", s, "is_top desc, top_date desc, publishTime desc,id desc", filter, pageable);
		}else if("2".equals(tab)) {//热门
			s = PropertyFilter.getSqlByFilterAndPageable("", s, "is_top desc, top_date desc, viewCount desc,publishTime desc,id desc", filter, pageable);
		}else if("3".equals(tab)) {//精华
			s = PropertyFilter.getSqlByFilterAndPageable("", s, "is_top desc, top_date desc, publishTime desc,id desc", filter, pageable);
		}else if("4".equals(tab)) {//评论
			s = PropertyFilter.getSqlByFilterAndPageable("", s, "is_top desc, top_date desc, lastReplyDate desc,publishTime desc,id desc", filter, pageable);
		}
		Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
		List<Map> list = page.getContent();
		ForumPost forum = null;
		for (Map map : list) {
			String authorId = StringUtils.null2String(map.get("author"));
			String lastReplyUserId = StringUtils.null2String(map.get("lastReplyUser"));
			map.put("authorName", cmpPopUserOrgName.getUserNameById(authorId));
			map.put("lastReplyUserName", cmpPopUserOrgName.getUserNameById(lastReplyUserId));
			if(!"".equals(StringUtils.null2String(map.get("lastReplyPostId")))) {
				forum = super.findOne(StringUtils.null2String(map.get("lastReplyPostId")));
			}else {
				forum = new ForumPost();
			}
			map.put("replyisanonymity", forum.getIsAnonymity());
			map.put("replyispetname", forum.getIsPetname());
			map.put("replypetname", forum.getPetname());
		}
		return new PageImpl<>(list, page.getPageable(), page.getTotalElements());
	}
	
	/**
	 * 所有帖子菜单查询
	 * @param title
	 * @param publishType
	 * @param typeId
	 * @param boardId
	 * @param author
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public Page<Map> searchAllPost1(String title,String publishType,String typeId,String boardId,
			String author,String startTime,String endTime,WebUser user,Pageable pageable,String tab,String searchType,List<PropertyFilter> filter,String mdpostType){
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		StringBuffer sql = new StringBuffer();
		Map<String, Object> values = new HashMap<String, Object>();
		sql.append(" SELECT id,publishType,isEssence,content,author,boardId,boardName,aplication_scope,title,fn_date_format(createdTime,'MM-dd HH:mm') createdDate,fn_date_format(topTime,'MM-dd HH:mm') top_date,type,is_top,isAnonymity,isPetname,petname,attId,");
		sql.append(" fn_date_format(lastReplyTime,'MM-dd HH:mm:ss') lastReplyDate,lastReplyUser,replyisanonymity,replyispetname,replypetname,isCopy,isRePost,isEditPost,viewCount,replyCount,isModerator,isCollection,publishTime,forumType ");
		if(StringUtils.isNotEmpty(author) || StringUtils.equals(searchType, "2")) {
			sql.append(" ,authorName ");
		}
		sql.append(" FROM ( select a.id,a.publishType,a.content,a.isEssence,a.boardName, a.boardid as boardId ,a.author, a.title,a.checkStatus ");
		//排序的时候createdDate需要年，展示的时候不需要年，所以oracle会报错，所以单独的将createdDate和top_date的数据拿出来 
		sql.append(" ,a.createdDate as createdTime,a.lastReplyDate as lastReplyTime,a.top_date as topTime,a.isCollection,fn_date_format(a.createdDate,'yyyy-MM-dd HH:mm:ss') createdDate,fn_date_format(a.top_date,'yyyy-MM-dd HH:mm:ss') top_date ");
		sql.append(" ,a.type, a.is_top,a.isCopy,a.isRePost,a.isEditPost, a.isAnonymity, a.isPetname,a.petname,a.attId, fn_date_format(a.lastReplyDate,'yyyy-MM-dd HH:mm:ss') lastReplyDate, a.lastReplyUser,a.is_anonymity as replyisanonymity,a.is_petname as replyispetname,a.replypetname, ");
		//sql.append(" CASE  WHEN (os.scopeValue = :userId or a.lastReplyUser = :userId or a.is_anonymity = 0) ");//最后评论人本人名称显示问题
		//sql.append(" CASE WHEN (a.is_anonymity = 1) ");
		//sql.append(" THEN '匿名' WHEN (a.is_petname = 1) THEN a.replypetname ELSE a.lastReplyUserName ");
		sql.append(" a.viewCount, a.replyCount, a.isModerator,a.publishTime, a.aplication_scope,a.forumType from ( ");
		sql.append(" select t.id AS boardid,t.aplication_scope,t.forumType,p.publist_type AS publishType,p.content,p.is_essence AS isEssence, t.name as boardName, p.id, p.author, p.title,p.check_status as checkStatus, p.createdDate, p.top_date, p.type,case when ofs.id is null then 0 else 1 end as isCollection, p.is_top, p.is_anonymity as isAnonymity,p.is_petname as isPetname, p.petname,p.att_id as attId, ");
		sql.append(" ps.last_reply_date as lastReplyDate,");
		sql.append(" p.is_copy as isCopy,p.is_re_post as isRePost,p.is_edit_post as isEditPost, ps.last_reply_user as lastReplyUser,ps.is_anonymity,ps.is_petname,ps.replypetname, ps.view_count as viewCount, ps.reply_count as replyCount,t.is_anonymity as boardIsAnonymity, t.isModerator,p.publish_time as publishTime  ");
		sql.append(" from oa_forum_post p ");
		sql.append(" inner JOIN  ");
		sql.append(" (select DISTINCT b.id, b.name ,b.is_anonymity ,b.aplication_scope,type1.name AS forumType, case when :userName = 'admin' then 1 WHEN s.id is not null then 1  else 0 end isModerator ");
		sql.append(" from oa_forum_board b ");
		sql.append(" inner join oa_forum_type type1 on b.forum_type = type1.id and type1.is_delete = 0 and type1.status = 1 ");
		sql.append(" LEFT JOIN oa_forum_moderator_scope s on b.id = s.fieldDataValue and s.fieldDataTable = 'oa_forum_board' and s.scopeType = 'user' and s.scopeValue = :userId ");
		sql.append(" where b.status = '1' and b.corp_id = :corpId and b.is_delete = 0 ) t on p.board_id = t.id ");
		sql.append(" left join oa_forum_scope ofs on ofs.fieldDataValue = p.is_collection and ofs.scopeValue = :userId ");
		sql.append(" LEFT JOIN (select y.id, y.post_id, y.last_reply_date, y.last_reply_user, y.view_count, y.reply_count,");
		// 判断是否显示匿名
		sql.append(" aa.is_anonymity,aa.is_petname,aa.petname as replypetname ");
		sql.append(" from oa_forum_post_statistics y ");
		//sql.append(" (select u.id, u.user_name as userName from sys_user u where u.corp_id = :corpId ");
		//sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId)  ");
		//sql.append(" u1 on y.last_reply_user = u1.id ");
		sql.append(" left join oa_forum_post aa on aa.id = y.last_reply_id and aa.corp_id = :corpId ) ");
		sql.append(" ps on p.id = ps.post_id ");
		//sql.append(" left join  ");
		//sql.append(" (select u.id, u.user_name as userName from sys_user u where u.corp_id = :corpId ");
		//sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		//sql.append(" on x.id = p.author ");
		sql.append(" where p.corp_id = :corpId and p.type = '1' and p.is_delete = 0 ");
		//精华页签(isEssence==1)
		if("3".equals(tab)) {
			sql.append(" and p.is_essence = '1' ");
		}
		if(StringUtils.isNotBlank(typeId)) {
			sql.append(" and p.board_id in ( select b.id from oa_forum_board b, oa_forum_type x where b.forum_type = x.id  ");
			sql.append(" and b.status = 1 and b.is_delete = 0 and b.corp_id = :corpId  and x.is_delete = 0   ");
			sql.append(" and x.status = 1 and x.corp_id = :corpId and b.forum_type= :typeId )");
			values.put("corpId", corpId);
			values.put("typeId", typeId);
		}
		if (StringUtils.isNotBlank(boardId) ) {
			sql.append(" and p.board_id = :boardId ");
			values.put("boardId", boardId);
		}
		sql.append(" and (p.check_status ="+ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue()+" or p.check_status ="+ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue()+")");
		sql.append(" ) a ");
		sql.append(" ) a ");
		if (StringUtils.isNotEmpty(author) || StringUtils.equals(searchType, "2")) {
			sql.append(" left join  ");
			sql.append(" (select u.id as userId, u.user_name as authorName from sys_user u where u.corp_id = :corpId ");
			sql.append(" union select a.id, a.trueName as authorName from sys_admin a where a.corp_id = :corpId) x ");
			sql.append(" on x.userId = a.author ");
		}
		sql.append(" where 1 = 1 ");
		if("1".equals(mdpostType)) {
			//适用版主sql匹配
			sql.append(" and (boardId in ( select fieldDataValue from oa_forum_moderator_scope where  fieldData='id' and fieldDataTable='oa_forum_board' and scopeValue in  (:userId))) " );
			values.put("userId", user.getUserId());
		}
		//评论页签不显示无回复帖子
		if("4".equals(tab)) {
			sql.append(" and a.replyCount > 0 ");
		}
		//发布类型查询
		if(StringUtils.isNotBlank(publishType)) {
			sql.append("and a.publishType = :publishType");
			values.put("publishType", publishType);
		}
		//点击版块导航的搜索框还是点击高级搜索再进行搜索
		if(StringUtils.equals(searchType, "2")) {
			title = SqlUtils.escapeNormalChars(title);
			author = SqlUtils.escapeNormalChars(author);
			if(StringUtils.equals(title, "匿名")) {
				sql.append(" and (a.title like '%"+title+"%' or (( authorName like '%"+author+"%')  or  (a.author <> :userId and a.isAnonymity = 1)))");
			}else {
				sql.append(" and (a.title like '%"+title+"%' or ( authorName like '%"+author+"%' and a.isPetname <> 1 ) or (a.petname like '%"+author+"%') and  (a.isAnonymity <> 1 or (a.author = :userId and a.isAnonymity = 1) or (a.author = :userId and a.isPetname = 1)))");
			}
		}else {
			//作者模糊查询
			if (StringUtils.isNotEmpty(author)) {
				author = SqlUtils.escapeNormalChars(author);
				if(StringUtils.equals(author, "匿名")) {
					sql.append(" and  (authorName like '%"+author+"%' ");
					sql.append(" or  (a.author <> :userId and a.isAnonymity = 1)) ");
				}else {
					sql.append(" and  ((authorName like '%"+author+"%' and a.isPetname <> 1 ) or (a.petname like '%"+author+"%'))");
					sql.append(" and  (a.isAnonymity <> 1 or (a.author = :userId and a.isAnonymity = 1)  or (a.author = :userId and a.isPetname = 1)) ");
				}
	        }
			//标题模糊查询
			if(StringUtils.isNotEmpty(title)) {
				sql.append(" and a.title like '%"+title+"%' ");
			}
		}
		//起止时间查询
		if(StringUtils.isNotBlank(startTime)) {
			startTime = startTime + " 00:00:00";
			Date start = null;
			try {
				SimpleDateFormat  sdf1 =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				start = sdf1.parse(startTime);
			}catch(Exception e) {
				e.printStackTrace();
			}
			sql.append(" and a.publishTime >= :startTime ");
			values.put("startTime", start);
		}
		if(StringUtils.isNotBlank(endTime)) {
			endTime = endTime + " 23:59:59";
			Date end = null;
			try {
				SimpleDateFormat  sdf2 =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				end = sdf2.parse(endTime);
			}catch(Exception e) {
				e.printStackTrace();
			}
			sql.append(" and a.publishTime <= :endTime ");
			values.put("endTime", end);
		}
		values.put("userId", userId);
		values.put("corpId", corpId);
		values.put("userName", user.getUserName());
		String s = sql.toString();
		//适用范围sql匹配
		String scopeSql = cmpApplyScopeService.getInScopeDataSql(userId, "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",values);
		s+= " and " + scopeSql;
		if("1".equals(tab)) {//最新
			s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.is_top desc, a.top_date desc, a.publishTime desc,a.id", filter, pageable);
		}else if("2".equals(tab)) {//热门
			s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.is_top desc, a.top_date desc, a.viewCount desc,a.publishTime desc,a.id", filter, pageable);
		}else if("3".equals(tab)) {//精华
			s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.is_top desc, a.top_date desc, a.publishTime desc,a.id", filter, pageable);
		}else if("4".equals(tab)) {//评论
			s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.is_top desc, a.top_date desc, a.lastReplyDate desc,a.publishTime desc,a.id", filter, pageable);
		}
		Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
		List<Map> list = page.getContent();
		for (Map map : list) {
			String authorId = StringUtils.null2String(map.get("author"));
			String lastReplyUserId = StringUtils.null2String(map.get("lastReplyUser"));
			map.put("authorName", cmpPopUserOrgName.getUserNameById(authorId));
			map.put("lastReplyUserName", cmpPopUserOrgName.getUserNameById(lastReplyUserId));
		}
		return new PageImpl<>(list, page.getPageable(), page.getTotalElements());
	}
	
	
	/**
	 * @param ids
	 * @return
	 * @Title: checkMyDelete
	 * @Description: 检测是否能够 我的评论页面是否能够删除
	 * @return: boolean
	 * @date 2017年11月21日 下午5:48:32
	 */
	public Map checkMyDelete(String[] ids) {
		String corpId = WebUtils.getCurrentUser().getCorpId();
		Map<String, Object> r = new HashMap<String, Object>();
		boolean flag = true;
		if (ids != null && ids.length > 0) {
			StringBuffer sql = new StringBuffer();
			sql.append(
					" select p.id, p.type, b.is_check as isCheck from oa_forum_post p, oa_forum_board b where p.board_id = b.id and p.corp_id = :corpId and p.id in (:ids) and p.is_delete = 0 and b.is_delete = 0 ");
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("corpId", corpId);
			paramMap.put("ids", Arrays.asList(ids));
			List<Map> result = super.findByListNativeQuery(sql.toString(), null, paramMap);
			if (!CollectionUtils.isEmpty(result)) {
				for (Map m : result) {
					if (StringUtils.equals(m.get("isCheck").toString(), "1")) {
						flag = false;
					}
				}
			}
			r.put("posts", result);
		}
		r.put("flag", flag);

		return r;
	}

	/**
	 * @param ids
	 * @param r
	 * @return
	 * @Title: deleteMyPost
	 * @Description: 帖子删除
	 * @return: OperationResult
	 * @date 2017年11月21日 下午8:30:44
	 */
	public OperationResult deleteMyPost(String[] ids, Map r) {
		Map resources = new HashMap();
		Assert.notNull(ids);
		Assert.notNull(r);
		List posts = (List) r.get("posts");
		List idList = Arrays.asList(ids);
		int c = 0;
		try {
			if (!CollectionUtils.isEmpty(posts)) {
				Iterator arg5 = posts.iterator();
				while (arg5.hasNext()) {
					Map m = (Map) arg5.next();
					String id = m.get("id").toString();
					if (idList.indexOf(id) > 0) {
						if (StringUtils.equals(m.get("type").toString(), "1")) {
							// 该记录为帖子信息
							if (forumPostDao.deleteMainpost(id) == 1) {
								c++;
							}
						} else if (StringUtils.equals(m.get("type").toString(), "2")) {
							// 该记录为回帖信息
							if (forumPostDao.deleteRepost(id) == 1) {
								c++;
							}
						}
					}
					idList.remove(id);
				}
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
			return c == 0 ? OperationResult.buildFailureResult("删除失败")
					: OperationResult.buildWarningResult("删除操作已处理. 成功:" + c + "条,失败:" + (ids.length - c) + "条", idList);

		}
		//国际化资源
		resources.put("i18NCode", "oa.forum.deletetips4");
		return c == ids.length ? OperationResult.buildSuccessResult("删除成功")
				: OperationResult.buildSuccessResult("成功删除所选取记录:" + ids.length + "条");
	}

	/**
	 * @param id
	 * @param corpId 
	 * @return
	 * @Title: findOnePost
	 * @Description: 编辑 帖详情时显示的内容
	 * @return: Map
	 * @date 2017年11月23日 下午4:10:47
	 */
	public Map findOnePost(String id, int type, String token, String appType, String corpId ,WebUser user) {

		StringBuffer sql = new StringBuffer();
			sql.append(
					" select p.id,p.publist_type as publistType, p.att_id as attId, p.author, p.board_id as boardId, p.content, p.createdBy, p.createdDate, p.createdOrg, p.is_anonymity as isAnonymity,p.is_petname as isPetname,p.check_status as checkStatus,");
			sql.append(
					" p.post_id as postId, p.publish_time as publishTime, p.title, p.is_top, p.type, p.optlock as version, p.corp_id as corpId, ");
			sql.append(
					" p.is_copy as isCopy,p.is_re_post as isRePost,p.is_edit_post as isEditPost,b.is_anonymity as boardIsAnonymity,b.is_petname as boardIsPetname,b.status AS boardStatus,t.status AS typeStatus from oa_forum_post p LEFT JOIN oa_forum_board b ON p.board_id = b.id  ");
			sql.append(
					" LEFT JOIN oa_forum_type t ON t.id = b.forum_type where p.id = :id and p.is_delete = 0 ");

//		Query query = getEntityManager().createNativeQuery(sql.toString()).setParameter(1, id);
//		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
//		List<Map> list = query.getResultList();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id",id);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, paramMap);
		
		List<ForumSensitive> sensitiveList =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : sensitiveList) {
			sList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}
		//敏感词
		/*List<ForumSensitive> sensitiveList =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : sensitiveList) {
			sList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}*/
		Map r = null;
		if(list != null && list.size() > 0) {
			r = list.get(0);
			r.put("content", super.findOne(r.get("id").toString()).getContent());
			//判断当前的版块是否还存在
			String boardId = r.get("boardId").toString();
		    boolean boardIsDelete = forumBoardService.boardIfDelete(boardId);
		    r.put("boardIsDelete", boardIsDelete);
		    //如果为草稿 版块置空,版块id置空
			//if(StringUtils.equals(r.get("checkStatus").toString(), "0")) {
				//r.put("boardId", "");
			//}
			boolean flag = false;
			if(WebUtils.getCurrentUser().getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(WebUtils.getCurrentUser())) {
				flag = true;
			}
			r.put("isAdminRole", flag);
			Object attIdJson;
			boolean isAuthor = false;
			if(StringUtils.equals(StringUtils.null2String(r.get("author")) , user.getUserId())) {
				isAuthor = true;
			}
			r.put("isAuthor", isAuthor);
			if (StringUtils.equals(appType, "dingding")) {
				attIdJson = transformAttachmentPlanform2Dd(StringUtils.null2String(r.get("attId")));
			} else {
				attIdJson = getAttachmentFile(r.get("attId"), token);
			}
			r.put("attIdJson", attIdJson);
		}
		return r;
	}
	
	public static String removeTag(String htmlStr) {
        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // script
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // style
        String regEx_html = "<[^>]+>"; // HTML tag
        String regEx_space = "\\s+|\t|\r|\n";// other characters

        Pattern p_script = Pattern.compile(regEx_script,
                Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll("");

        Pattern p_style = Pattern
                .compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll("");

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll("");

        Pattern p_space = Pattern
                .compile(regEx_space, Pattern.CASE_INSENSITIVE);
        Matcher m_space = p_space.matcher(htmlStr);
        htmlStr = m_space.replaceAll(" ");

        return htmlStr;

    }

	/**
	 * @param id
	 * @Title: topPost
	 * @Description: 帖子置顶
	 * @return: void
	 * @date 2017年11月24日 下午3:04:04
	 */
	public OperationResult topPost(String id) {
		WebUser user = WebUtils.getCurrentUser();
		ForumPost p = this.findOne(id);
		if (p.getIsTop() == 1) {
			//取消(主题)置顶积分
			if(p.getPublistType()!=null && p.getPublistType()==1 ) {
				if(p.getAuthor()!=null) {
					if(!"1".equals(p.getAuthor().toString())) {
						Map<String,Object> userMap = userApiService.getUser(p.getAuthor(), user.getCorpId(),"", user.getJwtToken());
						if(userMap!=null) {
							forumIntegralService.savePostIntegral(p.getAuthor(), userMap.get("userName").toString(), userMap.get("loginName").toString(), "3");
						}
					}else {
						forumIntegralService.savePostIntegral("1", "系统管理员", "admin", "3");
					}
				}
			}
			p.setIsTop(0);
			p.setTopDate(null);
		} else {
			//置顶(主题)积分
			if(p.getPublistType()!=null && p.getPublistType()==1 ) {
				if(p.getAuthor()!=null) {
					if(!"1".equals(p.getAuthor().toString())) {
						Map<String,Object> userMap = userApiService.getUser(p.getAuthor(), user.getCorpId(),"", user.getJwtToken());
						if(userMap!=null) {
							forumIntegralService.savePostIntegral(p.getAuthor(), userMap.get("userName").toString(), userMap.get("loginName").toString(), "2");
						}
					}else {
						forumIntegralService.savePostIntegral("1", "系统管理员", "admin", "2");
					}
				}
			}
			p.setIsTop(1);
			p.setTopDate(new Date());
		}
		this.save(p);
		return OperationResult.buildSuccessResult();
	}
	
	/**
	 * @Title: essencePost
	 * @Description: 帖子加精
	 * @param id
	 * @return
	 * @date 2019年09月16日 下午5:10:04
	 */
	public OperationResult essencePost(String id) {
		WebUser user = WebUtils.getCurrentUser();
		ForumPost p = this.findOne(id);
		if ("1".equals(p.getIsEssence())) {
			//取消(主题贴)精华积分
			if(p.getPublistType()!=null && p.getPublistType()==1 ) {
				if(p.getAuthor()!=null) {
					if(!"1".equals(p.getAuthor().toString())) {
						Map<String,Object> userMap = userApiService.getUser(p.getAuthor(), user.getCorpId(),"", user.getJwtToken());
						if(userMap!=null) {
							forumIntegralService.savePostIntegral(p.getAuthor(), userMap.get("userName").toString(), userMap.get("loginName").toString(), "5");
						}
					}else {
						forumIntegralService.savePostIntegral("1", "系统管理员", "admin", "5");
					}
				}
			}
			p.setIsEssence("0");
		} else {
			//设置(主题贴)精华积分
			if(p.getPublistType()!=null && p.getPublistType()==1 ) {
				if(p.getAuthor()!=null) {
					if(!"1".equals(p.getAuthor().toString())) {
						Map<String,Object> userMap = userApiService.getUser(p.getAuthor(), user.getCorpId(),"", user.getJwtToken());
						if(userMap!=null) {
							forumIntegralService.savePostIntegral(p.getAuthor(), userMap.get("userName").toString(), userMap.get("loginName").toString(), "4");
						}
					}else {
						forumIntegralService.savePostIntegral("1", "系统管理员", "admin", "4");
					}
				}
			}
			p.setIsEssence("1");
		}
		this.save(p);
		return OperationResult.buildSuccessResult();
	}


	/**
	 * @param onlyId 
	 * @param
	 * @return
	 * @Title: viewPost
	 * @Description: 查看帖子
	 * @return: List<Map>
	 * @date 2017年11月24日 下午7:56:10
	 */
	public Map viewPost(Pageable pageable, List<PropertyFilter> filter, ForumPost fp, String token, String currentPage,
			int status, String appType, String onlyId,String basicUrl) {
		WebUser user = WebUtils.getCurrentUser();
		String userId=user.getUserId();
		String corpId = user.getCorpId();
		//审核通过之后的帖子，非版主的小白发帖人是否可以编辑  但是不能删除的权限0表示非小白        小白是1   只有编辑权限
		//String chexkDelete="0";
		boolean isModerator = false;
		//ForumPost fp = this.findOne(postId);
		String postId = fp.getId();
		if(fp.getType() == 2) {
			postId = fp.getPostId();
		}else if(fp.getType() == 3) {
			ForumPost f  = this.findOne(fp.getPostId());
			postId = f.getPostId();
		}
		if (String.valueOf(status).equals(ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue())|| StringUtils.equals(String.valueOf(status), ForumPost.CheckStatusEnum.CHECK_STATUS_SHBTG.getValue())) {
			// 此时的id为oa_forum_check表的ID，页面为“我的帖子”，“审核帖子”;
			isModerator = forumBoardService.IsModeratorOfBoard(fp.getBoardId());
		} else {
			// 统计查看数量
			if(StringUtils.equals("1", onlyId)) {
				forumPostStatisticsService.addViewCount(user, postId);
			}
			isModerator = forumBoardService.IsModeratorOfBoard(fp.getBoardId());
		}
		if("admin".equals(user.getUserName())||user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())) {
			isModerator = true;
		}
		// 查询帖子的详情
		StringBuffer s1 = new StringBuffer();
		s1.append(" select t.id, t.recordId, fn_date_format(t.createdDate,'yyyy-MM-dd HH:mm:ss') createdDate,fn_date_format(t.publishTime,'yyyy-MM-dd HH:mm:ss') publishTime, t.type,t.rejection,t.isEssence, t.title,t.author, t.isAnonymity,t.isPetname,t.petname,  ");
		if(GlobalConstant.isOracle()) {
			s1.append(" replace(replace(t.content,chr(10),'\\n'),chr(13),'\\r') as content, t.isTop, t.board_id as boardId, t.attId, t.checkStatus, t.isCopy,t.isRePost , t.isEditPost,");
		}else{
			s1.append(" t.content, t.isTop, t.board_id as boardId, t.attId, t.checkStatus, t.isCopy,t.isRePost , t.isEditPost,");
		}
		s1.append(" b.name as boardName,b.status AS boardStatus,b.is_delete AS boardIsDelete,b.is_anonymity as isShowAnonymity,b.is_petname as isShowPetname,ofp.status AS typeStatus, ");
		s1.append(" case when ofs.id is null then 0 else 1 end as isCollection, ");
		s1.append(" s.view_count as viewCount, s.reply_count as replyCount,ofp.name as typeName  ");
		//s1.append(" s.view_count as viewCount, s.reply_count as replyCount,ofp.name as typeName,case when(obs.id is not null) then '1' ELSE '0' END AS canSendPost,oubs.countSend as countSend  ");
		s1.append(" from  ");
		s1.append(" (select p.id, p.id as recordId, p.createdDate,p.publish_time as publishTime, p.type,p.is_copy as isCopy,p.is_re_post as isRePost,p.is_edit_post as isEditPost, ");
		s1.append(" p.title, p.author, p.is_anonymity as isAnonymity,p.is_petname as isPetname, p.petname,p.content, p.is_top as isTop, ");
		s1.append(" p.board_id , p.att_id as attId,  p.check_status as checkStatus,p.is_collection,p.rejection,p.is_essence AS isEssence ");
		s1.append("  from oa_forum_post p where ");
		s1.append(" p.type = 1 and p.id = :pid and p.is_delete = 0 "); //and (p.check_status ='"+CHECK_STATUS_SHTG+"' or p.check_status = '"+CHECK_STATUS_WXSH+"' ) 
		s1.append(" ) t LEFT JOIN oa_forum_board b on b.id = t.board_id  ");
		//s1.append(" and b.is_delete = 0  ");
		s1.append(" LEFT JOIN oa_forum_type ofp on b.forum_type = ofp.id ");
		s1.append(" LEFT JOIN oa_forum_post_statistics s on s.post_id = t.id  ");
		s1.append(" left join oa_forum_scope ofs on ofs.fieldDataValue = t.is_collection and ofs.scopeValue = :author ");
		//可发帖人
		//s1.append(" LEFT JOIN (SELECT obs.id,obs.fieldDataValue FROM oa_forum_board_user_scope obs  WHERE obs.scopeValue = :author) obs ");
		//s1.append("  ON t.board_id = obs.fieldDataValue  ");
		//s1.append(" LEFT JOIN (SELECT count(oubs.fieldDataValue) as countSend,oubs.fieldDataValue FROM oa_forum_board_user_scope oubs group by oubs.fieldDataValue) oubs ");
		//s1.append("  ON t.board_id = oubs.fieldDataValue  ");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("author", user.getUserId());
		paramMap.put("pid", postId);
		List<Map> list = super.findByListNativeQuery(s1.toString(), null, paramMap);
		if(list==null || list.isEmpty()) {
			return null;
		}
		Map<String,Object> p = new HashMap<String, Object>();
		if(list != null && list.size() > 0) {
			p = (Map<String,Object>)list.get(0);
			if(StringUtils.equals(StringUtils.null2String(p.get("typeStatus")), "2")) {
				p.put("boardStatus", "2");				
			}
		}
		//判断是否有管理员权限
		boolean flag = false;
		if(user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
			flag = true;
		}
		
		p.put("isAdminRole", flag);
		//判断是否处在当前版块黑名单
		boolean blackListFlag = false;
		String boardId = StringUtils.null2String(p.get("boardId"));
		String moderatorStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope", "oa_forum_board", "id", boardId);
		if(moderatorStr.indexOf(user.getUserId()) == -1 && !flag) {
			String userStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_board_user_scope", "oa_forum_board", "id", boardId);
			if(StringUtils.isNotEmpty(userStr)) {
				List<String> allUserIds = cmpApplyScopeService.getAllOrgStaGrpIdsByUserId(user.getUserId());
				for(String id : allUserIds) {
					if(userStr.indexOf(id) != -1) {
						blackListFlag = true;
						break;
					}else {
						blackListFlag = false;
					}
				}
			}
		}
		p.put("blackListFlag", blackListFlag);
		//将图片处理成大图,不再用上传下载组件（处理主贴内容图片附件）
		List<String> attList = new ArrayList();
		String attids = StringUtils.null2String(p.get("attId"));
		if(StringUtils.isNotEmpty(attids)) {
			String[] picId = attids.split("\\|");
			for(String id : picId) {
				String Id = id.trim();
				String pic = this.getAttachmentFile(Id, token);
				List<Map> attachmentList = JsonUtils.readListValue(pic);
				Map attachment = attachmentList.get(0);
		        String imgUrl =  basicUrl + "/attachment/image?fid="+attachment.get("id")+"&chksum="+attachment.get("checksum");
		        attList.add(imgUrl);
			}
		}
		p.put("postAttList", attList);
		
		List<ForumSensitive> forumSensitiveList =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sensitiveList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : forumSensitiveList) {
			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}
		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		if(sensitiveList!=null&&sensitiveList.size()>0) {
			p.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, p.get("title").toString(), 2, "*"));
		}else {
			p.put("title", p.get("title").toString());
		}
		p.put("content", p.get("content").toString());
		//查询发帖人图像
		String author=StringUtils.null2String(p.get("author"));
		String isAnonymity=StringUtils.null2String(p.get("isAnonymity"));//如果是匿名就不去查了 1 匿名  0  实名
		Map<String, String> map=new HashMap<>();
		if("0".equals(isAnonymity)) {
			map.put("fileName", "");
			map.put("image", "");
		    //map=getImage(author,  corpId,  token);
		}else {
			map.put("fileName", "");
			map.put("image", "");
		}
		p.putAll(map);
		//单独查询，当前登录人的当前帖子是否是审核通过的帖子，如果是审核通过后的，给与辨识
		/*StringBuffer s5 = new StringBuffer();
		s5.append(" select a.id,a.check_status as checkStatus" );
		s5.append(" from oa_forum_post a  inner JOIN oa_forum_board b on a.board_id = b.id ");
		s5.append(" where a.id = :pid and a.author=:userId and a.is_delete = '0' and a.check_status = 1");
		Map<String, Object> paramMap2 = new HashMap<String, Object>();
		paramMap2.put("pid", postId);
		paramMap2.put("userId", userId);
		List<Map> r5 = super.findByListNativeQuery(s5.toString(), null, paramMap2);
		if(org.apache.commons.collections.CollectionUtils.isNotEmpty(r5)) {
			chexkDelete="1";
		}
		p.put("chexkDelete", chexkDelete);*/
		// 获取帖子的标签
		//p.put("labels", getOnePostLabel(postId));
		Object attIdJson;
		if (appType == "dingding") {
			attIdJson = transformAttachmentPlanform2Dd(StringUtils.null2String(p.get("attId")));
		} else {
			attIdJson = getAttachmentFile(p.get("attId"), token);
		}
		p.put("attIdJson", attIdJson);
		p.put("isModerator", isModerator);
		boolean isAuthor = StringUtils.equals(user.getUserId(), p.get("author").toString()) ? true : false;
		p.put("isAuthor", isAuthor);
		// 分页查询评论主贴的帖子数据信息
		StringBuffer s2 = new StringBuffer();
		if(isModerator) {//需要去掉审核的最新的
			s2.append(" select t.id,fn_date_format(t.createdDate,'yyyy-MM-dd HH:mm:ss') createdDate,t.type,t.post_id as postId,t.title, case when t.author = '"+userId+"' then 1 else 0 end isauthor, ");
			if(GlobalConstant.isOracle()) {
				s2.append(" t.author,t.is_anonymity as isAnonymity,t.is_petname as isPetname,t.petname,replace(replace(t.content,chr(10),'\\n'),chr(13),'\\r') as content,t.board_id as boardId,t.is_top,t.att_id as attId,t.check_status as checkStatus from ");
			}else {
				s2.append(" t.author,t.is_anonymity as isAnonymity,t.is_petname as isPetname,t.petname,t.content,t.board_id as boardId,t.is_top,t.att_id as attId,t.check_status as checkStatus from ");
			}
			s2.append(" oa_forum_post t where t.type = " + POST_TYPE_REPLY + " and t.post_id = :pid and t.is_delete = 0  ");
		}else {
			s2.append(" select t.id,fn_date_format(t.createdDate,'yyyy-MM-dd HH:mm:ss') createdDate,t.type,t.post_id as postId,t.title,case when t.author = '"+userId+"' then 1 else 0 end isauthor,  ");
			if(GlobalConstant.isOracle()) {
				s2.append(" t.author,t.is_anonymity as isAnonymity,t.is_petname as isPetname,t.petname,replace(replace(t.content,chr(10),'\\n'),chr(13),'\\r') as content,t.board_id as boardId,t.is_top,t.att_id as attId,t.check_status as checkStatus from ");
			}else {
				s2.append(" t.author,t.is_anonymity as isAnonymity,t.is_petname as isPetname,t.petname,t.content,t.board_id as boardId,t.is_top,t.att_id as attId,t.check_status as checkStatus from ");
			}
			s2.append(" oa_forum_post t where t.type = " + POST_TYPE_REPLY + " and t.post_id = :pid and t.is_delete = 0  ");
			
		}
		Map<String, Object> values = new HashMap<String, Object>();
		values.put("pid", postId);
		String s = s2.toString();
		s = PropertyFilter.getSqlByFilterAndPageable("t", s, "t.createdDate desc", filter, pageable);
		Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
		Iterator iterator = page.getContent().iterator();
		//评论主贴的回复列表数据
		StringBuffer s3 = new StringBuffer();
		List<Map> commentsList = null;
		paramMap = new HashMap<String,Object>();
		List<String> replyAuthorId = new ArrayList<String>();//主贴发帖人和评论人的id串
		while (iterator.hasNext()) {
			s3  = new StringBuffer();
			commentsList = new ArrayList<>();
			Map m = (Map) iterator.next();
			// 回帖的附件（处理主贴的回贴内容图片附件）
			m.put("title", m.get("title").toString());
			m.put("content", m.get("content").toString());
			//将图片处理成大图,不再用上传下载组件
			List<String> pinglunAttList = new ArrayList();
			String pinglunAttids = StringUtils.null2String(m.get("attId"));
			if(StringUtils.isNotEmpty(pinglunAttids)) {
				String[] picId = pinglunAttids.split("\\|");
				for(String id : picId) {
					String Id = id;
					String pic = this.getAttachmentFile(Id, token);
					List<Map> attachmentList = JsonUtils.readListValue(pic);
					Map attachment = attachmentList.get(0);
			        String imgUrl =  basicUrl + "/attachment/image?fid="+attachment.get("id")+"&chksum="+attachment.get("checksum");
			        pinglunAttList.add(imgUrl);
				}
 			}
			m.put("attList", pinglunAttList);
			replyAuthorId.add(StringUtils.null2String(m.get("author")));
			//List<ForumPost> postList = forumPostDao.getPostCount(m.get("id").toString());
			s3.append(" select a.id , fn_date_format(a.createdDate,'yyyy-MM-dd HH:mm:ss') as createdDate,a.post_id as postId,a.title, ");
			if(GlobalConstant.isOracle()) {
				s3.append(" a.author,a.is_anonymity as isAnonymity,a.is_petname as isPetname,a.petname,replace(replace(a.content,chr(10),'\\n'),chr(13),'\\r') as content,a.receiver");
			}else {
				s3.append(" a.author,a.is_anonymity as isAnonymity,a.is_petname as isPetname,a.petname,a.content,a.receiver ");
			}
			s3.append(" from oa_forum_post a where post_id = :id and is_delete = 0 and type = "+ POST_TYPE_REPLY_COMMENTS );
			//s3.append(" from oa_forum_post a LEFT JOIN oa_forum_board b ON a.post_id = :id WHERE a.board_id = b.id and a.is_delete = 0 and a.type = "+POST_TYPE_REPLY_COMMENTS);
			//s3.append(" from ( select id,createdDate,post_id,title,author,is_anonymity,is_petname,petname,content,receiver,board_id from oa_forum_post where post_id = :id and is_delete = 0 and type = "+ POST_TYPE_REPLY_COMMENTS +") a ");
			//s3.append(" LEFT JOIN oa_forum_board b ON a.board_id = b.id ");
			s3.append(" order by createdDate");
			paramMap.put("id", m.get("id").toString());
			List<Map> postList = super.findByListNativeQuery(s3.toString(), null, paramMap);
			if(!postList.isEmpty()&&postList.size()>0) {
				if(postList.size()>2) {
					commentsList.add(postList.get(0));
					commentsList.add(postList.get(1));
				}else {
					commentsList = postList;
				} 
				for (Map map2 : commentsList) {
					map2.put("mainPostCheckStatus",  StringUtils.null2String(m.get("checkStatus")));
					map2.put("isAdminRole", flag);
					if(StringUtils.equals(user.getUserId(), StringUtils.null2String(map2.get("author")))) {
						map2.put("isAuthor", true);
					}else {
						map2.put("isAuthor", false);
					}
					if (StringUtils.equals(map2.get("isAnonymity").toString(), "1")) {
						if (StringUtils.equals(user.getUserId(), StringUtils.null2String(map2.get("author"))) || flag) {
							// 版主、管理员、自己查看的时候显示真实姓名+匿名标注
							if (StringUtils.equals(StringUtils.null2String(map2.get("author")), "1")) {
								map2.put("authorName", "系统管理员(匿名)");
								map2.put("receiverName", "");
							} else {
								map2.put("authorName", cmpPopUserOrgName.getUserNameById(StringUtils.null2String(map2.get("author"))) + "(匿名)");
								map2.put("receiverName", "");
							}
						} else {
							map2.put("authorName", "匿名");
							map2.put("receiverName", "");
						}
					} else {
						if (StringUtils.equals(map2.get("isPetname").toString(), "1")) {
							String petname = map2.get("petname")+"";
							if (StringUtils.equals(user.getUserId(), StringUtils.null2String(map2.get("author"))) || flag) {
								// 版主、管理员、自己查看的时候显示真实姓名+昵称标注
								if (StringUtils.equals(StringUtils.null2String(map2.get("author")), "1")) {
									map2.put("authorName", "系统管理员("+petname+")");
									map2.put("receiverName", "");
								} else {
									map2.put("authorName", cmpPopUserOrgName.getUserNameById(StringUtils.null2String(map2.get("author"))) + "("+petname+")");
									map2.put("receiverName", "");
								}
							} else {
								map2.put("authorName", petname);
								map2.put("receiverName", "");
							}
						}else {
							if (StringUtils.equals(StringUtils.null2String(map2.get("author")), "1")) {
								map2.put("authorName", "系统管理员");
								map2.put("receiverName", "");
							} else {
								//Map us = findUserName(map2.get("author").toString());
								String username = cmpPopUserOrgName.getUserNameById(StringUtils.null2String(map2.get("author")));
								//receiver不为空代表这是回复评论,为空代表这是回复回帖
								if(map2.get("receiver")!=null ) {
									if(StringUtils.equals(map2.get("receiver").toString(), "1")) {
										map2.put("authorName", username);
										map2.put("receiverName", "@系统管理员");
									}else {
										ForumPost post = this.findOne(map2.get("receiver").toString());
										if(post != null) {
											//Map receivers = findUserName(post.getAuthor());
											map2.put("authorName", username);
											if (post!= null) {
												String receiverName = cmpPopUserOrgName.getUserNameById(StringUtils.null2String(post.getAuthor()));
												if (StringUtils.equals(StringUtils.null2String(post.getIsAnonymity()), "1")) {
													if(flag) {
														receiverName =receiverName+"(匿名)";
													}else {
														receiverName = "匿名";
													}
												}else if(StringUtils.equals(StringUtils.null2String(post.getIsPetname()), "1")) {
													if(flag) {
														receiverName = receiverName+"("+StringUtils.null2String(post.getPetname())+")";
													}else {
														receiverName = StringUtils.null2String(post.getPetname());
													}
												}
												map2.put("receiverName", "@"+receiverName);
											}else {
												map2.put("receiverName", "");
											}
										}else {
											map2.put("authorName", username);
											map2.put("receiverName", "");
										}
									}
								}else {
									map2.put("authorName", username);
									map2.put("receiverName", "");
								}
							}
						}
					}
				}
				m.put("commentsList", commentsList);
				m.put("commentsNum", postList.size());
			}else {
				m.put("commentsList", null);
				m.put("commentsNum", 0);
			}
		}
		Map<String, Object> reloadPage = new HashMap<String, Object>();
		// 回帖的附件
		Iterator it = page.getContent().iterator();
		while (it.hasNext()) {
			Map<String,Object> mit = (Map<String,Object>) it.next();
			Object subattIdJson;
			if (appType == "dingding") {
				subattIdJson = transformAttachmentPlanform2Dd(StringUtils.null2String(mit.get("attId")));
			} else {
				subattIdJson = getAttachmentFile(mit.get("attId"), token);
			}
			mit.put("title", mit.get("title").toString());
			mit.put("content", mit.get("content").toString());
			mit.put("attIdJson", subattIdJson);
			//将图片处理成大图,不再用上传下载组件
			List<String> pinglunAttList = new ArrayList();
			String pinglunAttids = StringUtils.null2String(mit.get("attId"));
			if(StringUtils.isNotEmpty(pinglunAttids)) {
				String[] picId = pinglunAttids.split("\\|");
				for(String id : picId) {
					String Id = id;
					String pic = this.getAttachmentFile(Id, token);
					List<Map> attachmentList = JsonUtils.readListValue(pic);
					Map attachment = attachmentList.get(0);
			        String imgUrl =  basicUrl + "/attachment/image?fid="+attachment.get("id")+"&chksum="+attachment.get("checksum");
			        pinglunAttList.add(imgUrl);
				}
 			}
			mit.put("attList", pinglunAttList);
			replyAuthorId.add(StringUtils.null2String(mit.get("author")));
			//回帖人的图像
			String replyAuthor=StringUtils.null2String(mit.get("author"));
			String replyisAnonymity=StringUtils.null2String(mit.get("isAnonymity"));//如果是匿名就不去查了 1 匿名  0  实名
			Map<String, String> replyimg=new HashMap<>();
			//isModerator || SecurityUtils.isSuperAdmin(user) if条件已被删除
			if(StringUtils.equals(user.getUserId(), StringUtils.null2String(mit.get("author"))) || "0".equals(replyisAnonymity)) {
				map.put("fileName", "");
				map.put("image", "");
				//replyimg=getImage(replyAuthor,  corpId,  token);
			}else {
				replyimg.put("fileName", "");
				replyimg.put("image", "");
			}
			mit.putAll(replyimg);
		}
		replyAuthorId.add(p.get("author").toString());
		// 获取回帖人的发帖数
		String s4 = " select p.author, count(p.id) as countAll,ofp.coun from oa_forum_post p  ";
		       s4 += "left join (select count(op.id) as coun ,op.author from oa_forum_post op  where op.type = :postType  AND op.author IN ( :replyAuthorId ) AND op.is_delete = 0 AND op.check_status IN ( :status ) group by op.author) ofp on ofp.author = p.author ";
		       s4 += "where p.type in (:postTypeAll) and p.author in (:replyAuthorId) and p.is_delete = 0 and p.check_status in (:status) group by p.author,ofp.coun";
		Map<String, Object> paramMap3 = new HashMap<String, Object>();
		paramMap3.put("postType", POST_TYPE_NEW);
		List<Integer> typelist = new ArrayList<>();
		typelist.add(POST_TYPE_NEW);
		typelist.add(POST_TYPE_REPLY);
		paramMap3.put("postTypeAll", typelist);
		List<String> checkStatus =new ArrayList<>();
		checkStatus.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		checkStatus.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		paramMap3.put("status", checkStatus);
		paramMap3.put("replyAuthorId", replyAuthorId);
		List<Map> r4 = super.findByListNativeQuery(s4.toString(), null, paramMap3);
		Map<String, Object> m4 = new HashMap<String, Object>();
		for (Map<String, Object> swapm : r4) {
			m4.put(swapm.get("author").toString(), swapm.get("coun")+";"+swapm.get("countAll"));
		}
		/*Map<String, String> replyAuthorParams = new HashMap<String, String>();
		replyAuthorParams.put("corpId", user.getCorpId());
		List<String> replyAuthorIdParam = new ArrayList<String>();
		for (String s22 : replyAuthorId) {
			if (!StringUtils.equals(s22, "1")) {
				replyAuthorIdParam.add(s22);
			}
		}*/
		//Map<String, Object> replyAuthorMap = utilQueryUserInfo2(StringUtils.join(replyAuthorIdParam, ","), user.getCorpId(), token);
		//Map<String, Object> replyAuthorOrgMap = utilQueryUserOrg(StringUtils.join(replyAuthorIdParam, ","), user.getCorpId(), token);
		// 将用户的 发帖数、所属机构，循环插入返回的结果集中
	    it = page.getContent().iterator();
		while (it.hasNext()) {
			Map<String, Object> mit = (Map<String, Object>) it.next();
			mit.put("content", mit.get("content"));
			String value = m4.get(mit.get("author")).toString();
			String[] valuesPost = value.split(";");
			Map userMap = cmpPopUserOrgName.getUserInfoById(StringUtils.null2String(mit.get("author")));
			if (StringUtils.equals(mit.get("isAnonymity").toString(), "1")) {
				if (StringUtils.equals(user.getUserId(), StringUtils.null2String(mit.get("author"))) || flag) {
					// 版主、管理员、自己查看的时候显示真实姓名+匿名标注
					mit.put("postCount", valuesPost[0]);
					mit.put("postCountAll", valuesPost[1]);
					if (StringUtils.equals(StringUtils.null2String(mit.get("author")), "1")) {
						mit.put("authorName", "系统管理员(匿名)");
						mit.put("userPhotoPath", GlobalConstant.getFlexServerPath(null) + "/web/dist/fui/images/admin.png");
					} else {
						mit.put("authorName", StringUtils.null2String(userMap.get("userName")) + "(匿名)");
						mit.put("userPhotoPath", (StringUtils.isBlank(StringUtils.null2String(userMap.get("imgId"))) ? GlobalConstant.getFlexOfficePageUrl(null) : GlobalConstant.getFlexServerPath(null)) + "/"
								+ getUserImage(userMap.get("sex"), userMap.get("imgId"), token));
					}
				} else {
					mit.put("postCount", "");
					mit.put("postCountAll", "");
					mit.put("orgName", "");
					mit.put("authorName", "匿名");
					mit.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
				}
			} else {
				mit.put("postCount", valuesPost[0]);
				mit.put("postCountAll", valuesPost[1]);
				if (StringUtils.equals(mit.get("isPetname").toString(), "1")) {
					String petname = mit.get("petname")+"";
					// 版主、管理员、自己查看的时候显示真实姓名+昵称标注
					if (StringUtils.equals(user.getUserId(), StringUtils.null2String(mit.get("author"))) || flag) {
						if (StringUtils.equals(StringUtils.null2String(mit.get("author")), "1")) {
							mit.put("authorName", "系统管理员("+petname+")");
							mit.put("userPhotoPath", GlobalConstant.getFlexServerPath(null) + "/web/dist/fui/images/admin.png");
						} else {
							mit.put("authorName",StringUtils.null2String(userMap.get("userName")) + "("+petname+")");
							mit.put("userPhotoPath", (StringUtils.isBlank(StringUtils.null2String(userMap.get("imgId"))) ? GlobalConstant.getFlexOfficePageUrl(null) : GlobalConstant.getFlexServerPath(null)) + "/"
									+ getUserImage(userMap.get("sex"), userMap.get("imgId"), token));
						}
					}else{
						mit.put("postCount", "");
						mit.put("postCountAll", "");
						mit.put("orgName", "");
						mit.put("authorName", petname);
						mit.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
					}
				}else {
					if (StringUtils.equals(StringUtils.null2String(mit.get("author")), "1")) {
						mit.put("authorName", "系统管理员");
						mit.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/admin.png");
					} else {
						mit.put("authorName", StringUtils.null2String(userMap.get("userName")));
						mit.put("userPhotoPath", (StringUtils.isBlank(StringUtils.null2String(userMap.get("imgId"))) ? GlobalConstant.getFlexOfficePageUrl(null) : GlobalConstant.getFlexServerPath(null) ) + "/"
								+ getUserImage(userMap.get("sex"), userMap.get("imgId"), token));
					}
				}
			}
			if(mit.get("userPhotoPath") == null && mit.get("authorName") == null) {
				mit.put("authorName","用户未找到");
				mit.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
			}
		}
		// 对原帖信息的匿名情况进行重新判断
		if(m4!=null && !m4.isEmpty()) {
			String value1 = m4.get(p.get("author")).toString();
			String[] valuesPost1 = value1.split(";");
			p.put("authorPostCount", valuesPost1[0]);
			p.put("authorPostCountAll", valuesPost1[1]);
		}
		Map mainUserMap = cmpPopUserOrgName.getUserInfoById(StringUtils.null2String(p.get("author")));
		if (StringUtils.equals(StringUtils.null2String(p.get("isAnonymity")), "0")) {
			
			if (StringUtils.equals(StringUtils.null2String(p.get("isPetname")), "1")) {
				String petname = p.get("petname")+"";
				if (isAuthor || flag) {
					// 昵称的情况下
					if (StringUtils.equals(StringUtils.null2String(p.get("author")), "1")) {
						p.put("authorOrgName", "");
						p.put("authorName", "系统管理员("+petname+")");
						p.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/admin.png");
					} else {
						p.put("authorName", StringUtils.null2String(mainUserMap.get("userName")) + "("+petname+")");
						p.put("userPhotoPath", (StringUtils.isBlank(StringUtils.null2String(mainUserMap.get("imgId"))) ? GlobalConstant.getFlexOfficePageUrl(null) : GlobalConstant.getFlexServerPath(null) ) + "/"
								+ getUserImage(mainUserMap.get("sex"), mainUserMap.get("imgId"), token));
					}
				}else {
					p.put("authorPostCount", "");
					p.put("authorPostCountAll	", "");
					p.put("authorOrgName", "");
					p.put("authorName", petname);
					p.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
				}
			}else {
				if (StringUtils.equals(StringUtils.null2String(p.get("author")), "1")) {
					p.put("authorOrgName", "");
					p.put("authorName", "系统管理员");
					p.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/admin.png");
				} else {
					p.put("authorName", StringUtils.null2String(mainUserMap.get("userName")));
					p.put("userPhotoPath", (StringUtils.isBlank(StringUtils.null2String(mainUserMap.get("imgId"))) ? GlobalConstant.getFlexOfficePageUrl(null) : GlobalConstant.getFlexServerPath(null) ) + "/"
							+ getUserImage(mainUserMap.get("sex"), mainUserMap.get("imgId"), token));
				}
			}
		} else {
			
			if (isAuthor || flag) {
				// 不匿名的情况下
				if (StringUtils.equals(StringUtils.null2String(p.get("author")), "1")) {
					p.put("authorOrgName", "");
					p.put("authorName", "系统管理员(匿名)");
					p.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/admin.png");
				} else {
					p.put("authorName", StringUtils.null2String(mainUserMap.get("userName")) + "(匿名)");
					p.put("userPhotoPath", (StringUtils.isBlank(StringUtils.null2String(mainUserMap.get("imgId"))) ? GlobalConstant.getFlexOfficePageUrl(null) : GlobalConstant.getFlexServerPath(null) ) + "/"
							+ getUserImage(mainUserMap.get("sex"), mainUserMap.get("imgId"), token));
				}
			} else {
				p.put("authorPostCount", "");
				p.put("authorPostCountAll	", "");
				p.put("authorOrgName", "");
				p.put("authorName", "匿名");
				p.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
			}
		}
		if(p.get("userPhotoPath") == null && p.get("authorName") == null) {
			p.put("authorName","用户未找到");
			p.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
		}
		reloadPage.put("content", page.getContent());
		reloadPage.put("number", page.getNumber());
		reloadPage.put("numberOfElements", page.getNumberOfElements());
		reloadPage.put("size", page.getSize());
		reloadPage.put("sort", page.getSort());
		reloadPage.put("totalElements", page.getTotalElements());
		reloadPage.put("totalPages", page.getTotalPages());
		reloadPage.put("currentPage", currentPage);
		Map<String, Object> r = new HashMap<String, Object>();
		r.put("post", p);
		r.put("page", reloadPage);
		r.put("boardName", p.get("boardName"));
		r.put("isShowAnonymity", p.get("isShowAnonymity"));
		r.put("isShowPetname", p.get("isShowPetname"));
		r.put("checkStatus", p.get("checkStatus"));
		//r.put("chexkDelete", p.get("chexkDelete"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return r;
	}


	/**
	 * 将钉钉的附件信息转换并,保存附件信息表,返回附件id(用 | 分割);
	 *
	 * @param attachment
	 * @return
	 */
	public String transformAttchmentDd2Platform(String attachment) {
		List<String> attrs = new ArrayList<>();
		WebUser user = WebUtils.getCurrentUser();
		if (StringUtils.isNotEmpty(attachment)) {
			JSONArray att = JSON.parseArray(attachment);
			for (int i = 0; i < att.size(); i++) {
				JSONObject o = att.getJSONObject(i);
				JSONObject d = new JSONObject();
				d.put("fileName", o.getString("fileName"));
				d.put("contentType", StringUtils.SPACE);
				d.put("fileSize", o.getString("fileSize"));
				d.put("fileExt", StringUtils.SPACE);
				d.put("relativePath", StringUtils.SPACE);
				d.put("clientIp", StringUtils.SPACE);
				d.put("dingSpaceId", o.getString("spaceId"));
				d.put("dingFileId", o.getString("fileId"));
				String s = JSON.toJSONString(d);
				Map attMap=attachmentUtilsService.createAttachmentInfo(s, user.getJwtToken());
                attrs.add(attMap.get("id")+"");
			}
		}
		String attids = StringUtils.join(attrs, "|");
		LOGGER.debug("att id is: " + attids);
		return attids;
	}

	/**
	 * 根据附件id获取到附件的具体信息,并封装成钉钉app适应的格式
	 * 
	 * @param attid
	 *            附件id用|分割
	 * @return
	 */
	public Object transformAttachmentPlanform2Dd(String attid) {
		Object data = new JSONArray();
		WebUser user = WebUtils.getCurrentUser();
		if (StringUtils.isNotEmpty(attid)) {
			Map param2 = new HashMap();
			param2.put("fids", attid);
			try {
				String scopeMap1 = restClient.get("/cmp/attachment/getAttachmentInfos", user.getJwtToken(), param2);
				Map<String, Object> map1 = JsonUtils.readValue(scopeMap1);
				if (StringUtils.equals("success", StringUtils.null2String(map1.get("type")))) {
					data = map1.get("data");
				}
			} catch (Exception e) {
				LOGGER.error("钉钉APP获取表单详情中的附件获取失败");
				LOGGER.error(e.getMessage());
			}
		}
		return data;
	}

	/**
	 * 根据帖子的匿名情况,判断 显示的姓名和头像
	 * 
	 * @param p
	 * @param authorMap
	 * @param user
	 * @param token
	 */
	public void judgeAnoymityUserInfo(Map p, Map authorMap, WebUser user, String token) {
		if (StringUtils.equals(StringUtils.null2String(p.get("isAnonymity")), "0")) {
			// 不匿名的情况下
			if (StringUtils.equals(StringUtils.null2String(p.get("author")), "1")) {
				p.put("authorName", "系统管理员");
				p.put("userPhotoPath", "fui/images/admin.png");
			} else {
				Map us = (Map) authorMap.get(p.get("author"));
				p.put("authorName", us.get("userName"));
				p.put("userPhotoPath", getUserImage(us.get("sex"), us.get("imgId"), token));
			}
		} else {
			if (StringUtils.equals(user.getUserId(), StringUtils.null2String(p.get("author")))) {
				// 不匿名的情况下
				if (StringUtils.equals(StringUtils.null2String(p.get("author")), "1")) {
					p.put("authorName", "系统管理员(匿名)");
					p.put("userPhotoPath", "fui/images/admin.png");
				} else {
					Map us = (Map) authorMap.get(p.get("author"));
					p.put("authorName", us.get("userName") + "(匿名)");
					p.put("userPhotoPath", getUserImage(us.get("sex"), us.get("imgId"), token));
				}
			} else {
				p.put("authorName", "匿名");
				p.put("userPhotoPath", "web/dist/fui/images/unknow.png");
			}
		}
	}

	public String getUserImage(Object sex, Object image, String token) {
		String Male = "web/dist/fui/images/male.png";
		String Female = "web/dist/fui/images/female.png";
		String Unknow = "web/dist/fui/images/unknow.png";
		String _image = StringUtils.null2String(image);
		if (StringUtils.isBlank(_image)) {
			String _sex = StringUtils.null2String(sex);
			if (StringUtils.equals(_sex, "male")) {
				return Male;
			} else if (StringUtils.equals(_sex, "female")) {
				return Female;
			} else {
				return Unknow;
			}
		} else {
			Map<String, String> att = attachmentUtilsService.getAttachmentByFileName(_image, token);
			if(att == null) {
				return _image;
			}
			String imageUrl = StringUtils.null2String(att.get("imageUrl"));
			if (StringUtils.isNotEmpty(imageUrl)) {
				return imageUrl.substring(1, imageUrl.length());
			} else {
				return _image;
			}
		}
	}

	/**
	 * @param id
	 * @return
	 * @Title: getOnePostLabel
	 * @Description: 根据id获取某个帖子的所有标签
	 * @return: List<Map>
	 * @date 2017年11月25日 下午1:21:08
	 */
	private List<Map> getOnePostLabel(String id) {
		String sql2 = "select pl.post_id as postId, l.id,l.createdBy,l.createdDate,l.createdOrg,l.lastModifiedBy,l.lastModifiedDate,l.lastModifiedOrg,"
				+ "l.name,l.color,l.status,l.sort_no,l.description,l.corp_id,l.is_delete"
				+ " from oa_forum_post_label pl left join oa_forum_label l on l.id = pl.label_id and l.is_delete = 0 and l.status = 1 where pl.post_id = :id order by sort_no, createdDate desc, name desc ";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		return super.findByListNativeQuery(sql2.toString(), null, paramMap);
	}

	/**
	 * @param postid
	 * @return
	 * @Title: isAuthorOfPost
	 * @Description: 判断当前用户是否为 post表中 帖子的作者
	 * @return: boolean
	 * @date 2017年11月28日 下午12:50:13
	 */
	public boolean isAuthorOfPost(String postId) {
		WebUser user = WebUtils.getCurrentUser();
		ForumPost forumPost =  forumPostDao.getPostByAuthor(user.getUserId(), postId);
		boolean flag = false;
		if (forumPost != null) {
			flag = true;
		}
		return flag;
	}

	/**
	 * @param id
	 * @return
	 * @Title: isAuthorOfPostCheck
	 * @Description: 基于post表和check表 混合检索，判断该用户是否为帖子的作者
	 * @return: boolean
	 * @date 2017年11月28日 下午2:54:51
	 */
	public boolean isAuthorOfPostCheck(String id) {
		WebUser user = WebUtils.getCurrentUser();
		StringBuffer s0 = new StringBuffer();
		s0.append(" select count(1) as coun from ( ");
		s0.append(" select p.id from oa_forum_post p where p.id = :id and p.author = :author and p.is_delete = 0 ) t ");
		/*s0.append(" union ");
		s0.append(
				" select c.id from oa_forum_check c where c.author = :author and (c.entity_id = :id or c.id = :id) and c.is_delete = 0 ) t ");*/
		Query q0 = this.getEntityManager().createNativeQuery(s0.toString()).setParameter("id", id)
				.setParameter("author", user.getUserId());
		int r0 = Integer.valueOf(q0.getSingleResult().toString());
		if (r0 > 0) {
			return true;
		}
		return false;
	}

	public String getAttachmentFile(Object attId, String token) {
		String attachment = StringUtils.null2String(attId);
		StringBuffer file = new StringBuffer();
		if (!"".equals(attachment)) {
			String result = attachmentUtilsService.getAttachmentInfo(attachment, token);
			file.append("[").append(result).append("]");
		}
		return file.toString();
	}

	/**
	 * @param ids
	 * @param logCode 
	 * @Title: addReplyCount
	 * @Description: 删除帖子、回帖
	 * @return: void
	 * @throws ParseException 
	 * @date 2017年11月27日 下午6:54:59
	 */
	public OperationResult deletePost(String[] ids, String logCode) throws ParseException {
		Map resources = new HashMap();
		List idList = Arrays.asList(ids);
		WebUser user = WebUtils.getCurrentUser();
		List<String> userBoards = forumBoardService.getUserBoards();
		StringBuffer s0 = new StringBuffer();
		s0.append(" select t.id, t.type, t.post_id, t.board_id, t.author,t.title, t.checkStatus,t.publist_type from ( ");
		s0.append(" select p.id, p.type, p.post_id, p.board_id, p.author,p.title,p.publist_type, ");
		s0.append("  p.check_status as checkStatus from oa_forum_post p where p.id in (:id) and p.corp_id = :corpId and p.is_delete = 0 ");
		s0.append(" ) t LEFT JOIN oa_forum_board b on t.board_id = b.id and b.is_delete = 0 ");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", idList);
		paramMap.put("corpId", user.getCorpId());
		List<Map> r0 = super.findByListNativeQuery(s0.toString(), null, paramMap);
		Iterator it0 = r0.iterator();
		List<String> error = new ArrayList<String>();
		//全文检索删除
		Map<String, String> allSearchMap = new HashMap<String,String>();
		Map<String, Object> obj = new HashMap<String,Object>();
		obj.put("ids", ids);
		try {
			restClient.post("/integ/fullsearch/searchServer/deleteServerInfo", user.getJwtToken(), allSearchMap, JSON.toJSONString(obj));
		}catch(Exception e) {
			e.printStackTrace();
		}
		while (it0.hasNext()) {
			Map m = (Map) it0.next();
				String s1 = "";
				String s2 = "";
				boolean isLoseReplyCount = true;
					if (Integer.parseInt(m.get("type").toString()) == POST_TYPE_REPLY) {
						//删除(主题)评论帖积分 7-删除评论
						if(m.get("publist_type")!=null && "1".equals(m.get("publist_type").toString())) {
							if(m.get("author")!=null) {
								if(!"1".equals(m.get("author").toString())) {
									Map<String,Object> userMap = userApiService.getUser(m.get("author").toString(), user.getCorpId(),"", user.getJwtToken());
									if(userMap!=null) {
										forumIntegralService.savePostIntegral(m.get("author").toString(), userMap.get("userName").toString(), userMap.get("loginName").toString(), "7");
									}
								}else {
									forumIntegralService.savePostIntegral("1", "系统管理员", "admin", "7");
								}
							}
						}
						s1 = " UPDATE oa_forum_post set is_delete = 1 where id = :id or post_id = :id ";
					} else if(Integer.parseInt(m.get("type").toString()) == POST_TYPE_REPLY_COMMENTS){
						s1 = " UPDATE oa_forum_post set is_delete = 1 where id = :id ";
					}else if(Integer.parseInt(m.get("type").toString()) == POST_TYPE_NEW ) {
						//删帖(主题)帖子积分(统计审核通过和无需审核的)
						if((m.get("publist_type")!=null && "1".equals(m.get("publist_type").toString()))&&("2".equals(m.get("checkStatus").toString()) || "4".equals(m.get("checkStatus").toString()))) {
							if(m.get("author")!=null) {
								if(!"1".equals(m.get("author").toString())) {
									Map<String,Object> userMap = userApiService.getUser(m.get("author").toString(), user.getCorpId(),"", user.getJwtToken());
									if(userMap!=null) {
										forumIntegralService.savePostIntegral(m.get("author").toString(), userMap.get("userName").toString(), userMap.get("loginName").toString(), "1");
									}
								}else {
									forumIntegralService.savePostIntegral("1", "系统管理员", "admin", "1");
								}
							}
						}
						s1 = " UPDATE oa_forum_post set is_delete = 1 where id = :id or post_id = :id ";
					}
				try {
					int n = this.getEntityManager().createNativeQuery(s1).setParameter("id", m.get("id"))
							.executeUpdate();
					if(Integer.parseInt(m.get("type").toString()) == POST_TYPE_NEW) {
						StringBuffer s4 = new StringBuffer();
						s4.append(" select id from oa_forum_post where post_id = ?1 ");
						Query q0 = this.getEntityManager().createNativeQuery(s4.toString()).setParameter(1,m.get("id"));
						List<String> r = q0.getResultList();
						if (r != null && !r.isEmpty()) {
							s2 = " UPDATE oa_forum_post set is_delete = 1 where post_id in (:id) and type = "+POST_TYPE_REPLY_COMMENTS;
							int n3 = this.getEntityManager().createNativeQuery(s2).setParameter("id", r)
									.executeUpdate();
							s2 = "";
						}
					}
					if (StringUtils.isNotBlank(s2)) {
						int n2 = this.getEntityManager().createNativeQuery(s2).setParameter("id", m.get("id"))
								.executeUpdate();
					}
				} catch (Exception e) {
					LOGGER.error(e.getMessage());
					error.add(m.get("id").toString());
				}
				if (isLoseReplyCount) {
					// 回帖数减少一
					if (Integer.parseInt(m.get("type").toString()) == POST_TYPE_NEW||Integer.parseInt(m.get("type").toString()) == POST_TYPE_REPLY_COMMENTS) {
					} else {
						forumPostStatisticsService.subtractReplyCount(m.get("post_id"));
					}
				}
				int type = Integer.parseInt(m.get("type").toString());
				if(Integer.parseInt(m.get("type").toString()) == POST_TYPE_NEW ) {
					logService.saveModuleLog(logCode, StringUtils.null2String(m.get("title")), ""); 
				}
		}
		if (ids.length == 0) {
			//国际化资源
			resources.put("i18NCode", "oa.forum.seldata");
			return OperationResult.buildFailureResult("请选择相关数据",resources);
		} else {
			ForumPostSendUtils.deleteMessage(idList,user.getCorpId(),user.getJwtToken());
			if (error.size() > 0) {
				return error.size() == ids.length ? OperationResult.buildFailureResult("删除失败")
						: OperationResult.buildWarningResult(
								"删除操作已处理. 成功:" + (ids.length - error.size()) + "条,失败:" + error.size() + "条", error);
			} else {
				//国际化资源
				resources.put("i18NCode", "oa.forum.deletetips4");
				return ids.length == 1 ? OperationResult.buildSuccessResult("删除成功",resources)
						: OperationResult.buildSuccessResult("删除成功",resources);
			}
		}
	}
	
	/**
	 * @param postid
	 * @param orderDate
	 *            按照发布时间（记录的createdDate字段）排序 1:正序，2：倒序
	 * @Title: getReplyByPostid
	 * @Description: 根据帖子id获取所以回帖
	 * @return: void
	 * @date 2017年11月27日 下午6:54:59
	 */
	public List<ForumPost> getReplyByPostid(String postid, int orderDate) {
		StringBuffer s = new StringBuffer();
		s.append("select p from ForumPost p where p.postId = :id and p.isDelete = 0 and p.corpId = :cid order by p.createdDate ");
		if (orderDate == 2) {
			s.append(" desc ");
		}
		List<ForumPost> fplist = this.getEntityManager().createQuery(s.toString()).setParameter("id", postid)
				.setParameter("cid", WebUtils.getCurrentUser().getCorpId()).getResultList();
		return fplist;
	}
	
	/**
	 * 分页结果拼装 创建人姓名
	 *
	 * @param page
	 * @param token
	 * @param corpId
	 * @param idFieldName
	 * @param nameFieldName
	 */
	private void findPageListCreatedName(Page<Map> page, String token, String corpId, String idFieldName,
			String nameFieldName) {
		List<String> ids = new ArrayList<String>();
		String nameField = StringUtils.isNotBlank(nameFieldName) ? nameFieldName : "createdName";
		String idField = StringUtils.isNotBlank(idFieldName) ? idFieldName : "createdBy";
		Iterator it = page.getContent().iterator();
		while (it.hasNext()) {
			Map m = (Map) it.next();
			if (!StringUtils.equals(StringUtils.null2String(m.get(idField)), "1")) {
				ids.add(StringUtils.null2String(m.get(idField)));
			}
		}
		Map<String, String> textParams = new HashMap<String, String>();
		textParams.put("corpId", corpId);
		textParams.put("id", StringUtils.join(ids, ","));
		List<Map<String, Object>> userMap = userApiService.getUserRelatedInfo(StringUtils.join(ids, ","), "", corpId,
				token);
		it = page.getContent().iterator();
		while (it.hasNext()) {
			Map m = (Map) it.next();
			if (StringUtils.equals(StringUtils.null2String(m.get(idField)), "1")) {
				m.put(nameField, "系统管理员");
			} else {
				if (userMap != null && userMap.size() > 0) {
					m.put(nameField, userMap.get(0).get(StringUtils.null2String(m.get(idField)) + "user"));
				}
			}
		}
	}

	/**
	 * @param boards
	 * @param corpId
	 * @param showNumber
	 * @return
	 */
	public List<Map> getBoardPostList(String token, List<String> boards, String corpId, String showNumber) {
		StringBuffer sql = new StringBuffer();
		if("0".equals(showNumber)) {
			sql.append("select b.id as moduleId, b.name as moduleName from oa_forum_board b ");
			sql.append(" where b.is_delete = 0 and b.corp_id = :corpId ");
			if (!CollectionUtils.isEmpty(boards)) {
				sql.append(" and b.id = :boards ");
			}
			sql.append(" order by b.sort_no, b.id desc");
		}else {
			sql.append(
					" select b.id as moduleId, b.name as moduleName, p.id, p.title as subject, p.createdBy as authorId,p.is_petname as ispetname,p.petname,p.createdDate as \"date\", p.is_top as isTop ");
			sql.append(
					" from oa_forum_board b left join oa_forum_post p on b.id = p.board_id and p.type = 1 and p.is_delete = 0 and p.corp_id = :corpId  ");
			sql.append(" and p.check_status in (:status) ");
			sql.append(" where b.is_delete = 0 and b.corp_id = :corpId and b.status = 1 ");
			if (!CollectionUtils.isEmpty(boards)) {
				sql.append(" and b.id = :boards ");
			}
			sql.append(" order by b.sort_no, b.id, p.is_top desc, p.createdDate desc ");
		}
		List<Map> boardList = new ArrayList<Map>();
		Map boardDateMap = new HashMap();
		if (!CollectionUtils.isEmpty(boards)) {
			for (String s : boards) {
				if (StringUtils.isNotBlank(s)) {
					Map<String, Object> paramMap = new HashMap<String, Object>();
					paramMap.put("corpId", corpId);
					paramMap.put("boards", s);
					List<Map> res = new ArrayList<Map>();;
					if("0".equals(showNumber)) {
						res = super.findByListNativeQuery(sql.toString(), null, paramMap);
					}else {
						List<String> statusList = new ArrayList<>();
						statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
						statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
						paramMap.put("status", statusList);
						res = super.findByListNativeQuery(sql.toString(), null, paramMap, 0, Integer.parseInt(showNumber));
					}
					List<String> authodIds = new ArrayList<String>();
					List<String> postIds = new ArrayList<String>();
					List<String> boardIDList = new ArrayList<String>();
					Iterator it = res.iterator();
					while (it.hasNext()) {
						Map m = (Map) it.next();
						postIds.add(StringUtils.null2String(m.get("id")));
						authodIds.add(StringUtils.null2String(m.get("authorId")));
						if (boardIDList.indexOf(StringUtils.null2String(m.get("moduleId"))) < 0) {
							boardIDList.add(StringUtils.null2String(m.get("moduleId")));
							Map bw = new HashMap();
							bw.put("moduleId", StringUtils.null2String(m.get("moduleId")));
							bw.put("moduleName", StringUtils.null2String(m.get("moduleName")));
							boardList.add(bw);
						}
					}
					// 处理 帖子标签
					Map lablesMap = new HashMap();
					if (!CollectionUtils.isEmpty(postIds)) {
						String s2 = " select pl.post_id, l.id as tagId, l.name as tagName, l.color as tagColor from oa_forum_label l, oa_forum_post_label pl where l.id = pl.label_id and pl.post_id in (:pid) and l.is_delete = 0 order by pl.post_id, l.sort_no, l.createdDate desc, l.name desc ";
						Map<String, Object> paramMap2 = new HashMap<String, Object>();
						paramMap2.put("pid", postIds);
						List<Map> lables = super.findByListNativeQuery(s2.toString(), null, paramMap2);
						Iterator it2 = lables.iterator();
						String swapLid = "";
						List<Map> swapLable = new ArrayList<Map>();
						while (it2.hasNext()) {
							Map l = (Map) it2.next();
							Map lw = new HashMap();
							String post_id = StringUtils.null2String(l.get("post_id"));
							if (!StringUtils.equals(swapLid, post_id)) {
								lablesMap.put(swapLid, swapLable);
								swapLable = new ArrayList<Map>();
							}
							lw.put("tagId", StringUtils.null2String(l.get("tagId")));
							lw.put("tagName", StringUtils.null2String(l.get("tagName")));
							lw.put("tagColor", StringUtils.null2String(l.get("tagColor")));
							swapLable.add(lw);
							swapLid = post_id;
						}
						lablesMap.put(swapLid, swapLable);
					}
					// 处理帖子作者姓名
					Map<String, String> userMap = utilQueryUserName(StringUtils.join(authodIds, ","), corpId, token);
					it = res.iterator();
					String boardId = "";
					List<Map> boardDateList = new ArrayList<Map>();
					while (it.hasNext()) {
						Map m = (Map) it.next();
						// 添加标签信息
						m.put("tag", null == lablesMap.get(m.get("id")) ? new ArrayList() : lablesMap.get(m.get("id")));
						// 添加作者姓名
						if("1".equals(StringUtils.null2String(m.get("ispetname")))) {
							m.put("author",StringUtils.null2String(m.get("petname")));
						}else {
							m.put("author", userMap.get(StringUtils.null2String(m.get("authorId"))));
						}
						if (StringUtils.equals(boardId, StringUtils.null2String(m.get("moduleId")))) {
							if (StringUtils.isNotBlank(StringUtils.null2String(m.get("id")))) {
								boardDateList.add(m);
							}
						} else {
							if (StringUtils.isBlank(boardId)) {
								if (StringUtils.isNotBlank(StringUtils.null2String(m.get("id")))) {
									boardDateList.add(m);
								}
							} else {
								boardDateMap.put(boardId, boardDateList);
								boardDateList = new ArrayList<Map>();
							}
							boardId = StringUtils.null2String(m.get("moduleId"));
						}
					}
					boardDateMap.put(boardId, boardDateList);
				}
			}
		}
		List resultList = new ArrayList();
		Iterator it3 = boardList.iterator();
		while (it3.hasNext()) {
			Map m = (Map) it3.next();
			m.put("moduleData", null == boardDateMap.get(StringUtils.null2String(m.get("moduleId"))) ? new ArrayList()
					: boardDateMap.get(StringUtils.null2String(m.get("moduleId"))));
			resultList.add(m);
		}
		return resultList;
	}

	/**
	 * just get username, haven't another infomation
	 *
	 * @param ids
	 * @param corpId
	 * @param token
	 * @return
	 */
	public Map<String, String> utilQueryUserName(String ids, String corpId, String token) {
		Map<String, String> result = new HashMap<String, String>();
		if (StringUtils.isNotEmpty(ids)) {
			boolean hasAdmin = false;
			List<String> idsList = new ArrayList<String>();
			String[] idarray = ids.split(",");
			for (String i : idarray) {
				if (!StringUtils.equals(i, "1")) {
					idsList.add(i);
				} else {
					hasAdmin = true;
				}
			}
			List<Map<String, Object>> userMap = userApiService.getUserList(ids, corpId, "", token);
			Iterator it = userMap.iterator();
			while (it.hasNext()) {
				Map m = (Map) it.next();
				result.put(StringUtils.null2String(m.get("id")), StringUtils.null2String(m.get("userName")));
			}
			if (hasAdmin) {
				result.put("1", "系统管理员");
			}
		}
		return result;
	}

	/**
	 * 获取用户机构性别等信息，不会获取admin的相关信息
	 *
	 * @param ids
	 * @param corpId
	 * @param token
	 * @return
	 */
	public Map<String, Object> utilQueryUserOrg(String ids, String corpId, String token) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			if (StringUtils.isNotEmpty(ids)) {
				boolean hasAdmin = false;
				List<String> idsList = new ArrayList<String>();
				String[] idarray = ids.split(",");
				for (String i : idarray) {
					if (!StringUtils.equals(i, "1")) {
						idsList.add(i);
					} else {
						hasAdmin = true;
					}
				}
				List<Map<String, Object>> userInfo = userApiService.getUserRelatedInfo(StringUtils.join(idsList, ","),
						"", corpId, token);
				Iterator it = userInfo.iterator();
				while (it.hasNext()) {
					Map m = (Map) it.next();
					result.put(StringUtils.null2String(m.get("userId")), m);
				}
			}
		} catch (Exception e) {
			LOGGER.error("获取用户机构性别等信息error", e);
		} finally {
			return result;
		}
	}

	public Map<String, Object> utilQueryUserInfo(String ids, String corpId, String token) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			if (StringUtils.isNotEmpty(ids)) {
				boolean hasAdmin = false;
				List<String> idsList = new ArrayList<String>();
				String[] idarray = ids.split(",");
				for (String i : idarray) {
					if (!StringUtils.equals(i, "1")) {
						idsList.add(i);
					} else {
						hasAdmin = true;
					}
				}
				List<Map<String, Object>> userMap = userApiService.getUserList(ids, corpId, "", token);
				Iterator it = userMap.iterator();
				while (it.hasNext()) {
					Map m = (Map) it.next();
					result.put(StringUtils.null2String(m.get("id")), m);
				}
			}
		} catch (Exception e) {
			LOGGER.error("获取用户信息error", e);
		} finally {
			return result;
		}
	}
	
	public Map<String, Object> utilQueryUserInfo2(String ids, String corpId, String token) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			if (StringUtils.isNotEmpty(ids)) {
				boolean hasAdmin = false;
				List<String> idsList = new ArrayList<String>();
				String[] idarray = ids.split(",");
				for (String i : idarray) {
					if (!StringUtils.equals(i, "1")) {
						idsList.add(i);
					} else {
						hasAdmin = true;
					}
				}
				//可查到被删除用户
				List<Map<String, Object>> userMap = userApiService.getUserListIncludeDel(ids, corpId, "", token);
				Iterator it = userMap.iterator();
				while (it.hasNext()) {
					Map m = (Map) it.next();
					result.put(StringUtils.null2String(m.get("id")), m);
				}
			}
		} catch (Exception e) {
			LOGGER.error("获取用户信息error", e);
		} finally {
			return result;
		}
	}
	
	//获取每个人的图像
	public Map<String, String> getImage(String userId, String corpId, String token) {
		Map<String, String> map = new HashMap<>();
		//Map<String, Object> scopeName = this.userApiService.getUser(userId, corpId, "", token);
		Map scopeName = findUserName(userId);
		if(scopeName!=null) {
			map.put("fileName", StringUtils.null2String(scopeName.get("img_id")));
			String fileName = StringUtils.null2String(map.get("fileName"));
			if (!"".equals(fileName)) {
				Map<String, String> image = this.attachmentUtilsService.getAttachmentByFileName(fileName, token);
				if (image != null && !image.isEmpty()) {
					map.put("image", image.get("id"));
				} else {
					map.put("image", "");
				}
			} else {
				map.put("image", "");
			}
		}else {
			map.put("image", "");
		}
		return map;
	}

	//==========================================以下钉钉方法======================================================================

	/**
	 * @param page
	 * @param pageSize
	 * @param corpId
	 * @param checkStatus 
	 * @return
	 * @Title: myPostList
	 * @Description: 分页获取“我的帖子”页面信息
	 * @return: Page<Map>
	 * @date 2017年11月21日 下午3:59:56
	 */
	public List<Map> myPostListDing(String page, String pageSize, String token, String corpId, String type, String title, String checkStatus) {
		int pageSizeInt = Integer.parseInt(pageSize);
		int start = (Integer.parseInt(page)-1)*pageSizeInt;
		WebUser user = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		StringBuffer sql = new StringBuffer();
		sql.append(" select a.id, a.attId,a.title, a.boardId, a.author, a.postId,a.publishTime, fn_date_format(a.createdDate,'MM-dd HH:mm') createdDate, a.type, a.checkStatus, a.entityId, a.authorName , a.boardName,a.isCheck, a.lastReplyUser, fn_date_format(a.lastReplyDate,'MM-dd HH:mm') lastReplyDate, a.viewCount, a.replyCount, a.isModerator,a.boardIsDelete,a.boardStatus,case when (a.author = :author) then 1 else 0 end as isAuthor,a.typeName ");
		sql.append(" from ( ");
		sql.append(" select t.id,t.attId, t.title, t.boardId, t.author, t.postId, t.createdDate,t.publishTime, t.type, t.checkStatus, t.entityId, ");
		sql.append(" x.userName as authorName , b.name as boardName,b.is_check as isCheck, b.is_delete AS boardIsDelete,b.status AS boardStatus, case when :userName = 'admin' then 1 WHEN ss.id is not null then 1  else 0 end isModerator , s.last_reply_user as lastReplyUser, s.last_reply_date as lastReplyDate, s.view_count as viewCount, s.reply_count as replyCount,type.name as typeName");
		sql.append(" from ( ");
		sql.append(" select p.id,p.att_id attId, p.title, p.board_id as boardId, p.author, p.post_id as postId, p.createdDate, p.type, p.check_status as checkStatus, p.id as entityId,p.publish_time as publishTime ");
		sql.append(" from oa_forum_post p where  p.corp_id = :corpId and p.author = :author and p.is_delete = 0 and p.type in (:type) ");
		/*sql.append(" UNION  ");
		sql.append(" select  c.id,c.att_id attId, c.title, c.board_id as boardId, c.author, c.post_id as postId, c.createdDate, c.type, c.check_status as checkStatus, c.entity_id as entityId ");
		sql.append(" from oa_forum_check c where c.corp_id = :corpId and c.check_status = '1' and c.author = :author and c.is_delete = 0 and c.type = :type ");*/
		sql.append(" ) t ");
		if(StringUtils.equals("1", type)) {
			//对我发表的进行修改,被删除的版块下存在的审核未通过的帖子也要显示出来(由于版块下存在状态为审核中,审核通过,无需审核的就无法删除版块-->被删除版块下帖子没被删除的只剩下未通过的和草稿,草稿这里不需要,所以断定这里只需要把is_delete判定就可以)
			//2.3版本,我的帖子可以显示被禁用得版块下的帖子 但不能编辑;如果版块既被删除又被禁用,帖子也不能编辑
			sql.append(" inner join oa_forum_board b on t.boardId = b.id  ");
			//sql.append(" and b.status = 1 ");
		}else {
			//2.4我回复的显示版块被禁用下帖子
			sql.append(" inner join oa_forum_board b on t.boardId = b.id and b.is_delete = 0   ");
			//sql.append(" and b.status = 1 ");
		}
		sql.append(" inner join oa_forum_type type on b.forum_type = type.id and type.is_delete = 0 ");
		sql.append(" LEFT JOIN oa_forum_moderator_scope ss on b.id = ss.fieldDataValue and ss.fieldDataTable = 'oa_forum_board' and ss.scopeType = 'user' and ss.scopeValue = :author ");
		sql.append(" left join  ");
		sql.append(" (select u.id, u.user_name as userName from sys_user u where u.is_delete = 0 and u.corp_id = :corpId ");
		sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		sql.append(" on x.id = t.author ");
		sql.append(" LEFT JOIN (select y.id, y.post_id, y.last_reply_date, y.last_reply_user, y.view_count, y.reply_count, u1.userName as lastReplyUserName from oa_forum_post_statistics y left join ");
		sql.append(" (select u.id, u.user_name as userName from sys_user u where u.is_delete = 0 and u.corp_id = :corpId ");
		sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId)  ");
		sql.append(" u1 on y.last_reply_user = u1.id ) s on t.entityId = s.post_id ");
		sql.append(" ) a where 1 = 1 ");
		if(StringUtils.isNotEmpty(title)) {
			sql.append(" and a.title like "+SqlUtils.escapeLikeValue(title));
		}
		sql.append(" and a.checkStatus in (:status)");
		sql.append(" ORDER BY a.publishTime desc,a.id");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("corpId", corpId);
		paramMap.put("author", userId);
		List<String> statusList = new ArrayList<>();
		if(StringUtils.isEmpty(checkStatus)) {
			statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
			statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
			statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHBTG.getValue());
			statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		}else if(StringUtils.equals(checkStatus, CheckStatusEnum.CHECK_STATUS_WSH.getValue())) {
			statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
		}else if(StringUtils.equals(checkStatus, CheckStatusEnum.CHECK_STATUS_SHTG.getValue())) {
			statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		}else if(StringUtils.equals(checkStatus, CheckStatusEnum.CHECK_STATUS_SHBTG.getValue())) {
			statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHBTG.getValue());
		}else if(StringUtils.equals(checkStatus, CheckStatusEnum.CHECK_STATUS_WXSH.getValue())) {
			statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		}
		paramMap.put("status", statusList);
		List<Integer> typeList = new ArrayList<>();
		if(!StringUtils.isNotBlank(type)|| StringUtils.equals(type, "1")) {
			typeList.add(POST_TYPE_NEW);
			paramMap.put("type",  typeList );
		}else if( StringUtils.equals(type, "2")) {
			typeList.add(POST_TYPE_REPLY);
			typeList.add(POST_TYPE_REPLY_COMMENTS);
			paramMap.put("type",  typeList );
		}
		//paramMap.put("type", StringUtils.isNotBlank(type) ? type : POST_TYPE_NEW);
		paramMap.put("userName", user.getUserName());
		List<Map> r = super.findByListNativeQuery(sql.toString(), null, paramMap, start, pageSizeInt);
		List<String> bs = forumBoardService.getUserBoards();
		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sensitiveList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : list) {
			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}
		Iterator it = r.iterator();
		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
//		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		//  我的帖子只需要查一次
		//每一条帖子的发帖人图像进行查询=====userId应为每个发帖人的userID,并非当前登录人的
		Map<String, String> map=getImage(userId,  corpId,  token);
		while (it.hasNext()) {
			Map m = (Map) it.next();
			int imageNum = 0;
			String attId = StringUtils.null2String(m.get("attId"));
			if(attId !=null&&StringUtils.isNotBlank(attId)) {
				imageNum =  attId.split("\\|").length;
			}
			m.put("imageNum", imageNum);
			if (!CollectionUtils.isEmpty(bs) && null != m) {
				if (bs.indexOf(m.get("boardId").toString()) >= 0) {
					m.put("isModerator", 1);
				}
			}
			if(sensitiveList!=null&&sensitiveList.size()>0) {
				m.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, m.get("title").toString(), 2, "*"));
			}else {
				m.put("title", m.get("title").toString());
			}
			//敏感词替换
//			if(sensitiveList!=null&&sensitiveList.size()>0) {
//				m.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, m.get("title").toString(), 2, "*"));
//			}
			
			m.putAll(map);
			m.put("attIdJson", transformAttachmentPlanform2Dd(StringUtils.null2String(m.get("attId"))));
		}
		return r;
	}
	
	/**
	 * @param page
	 * @param pageSize
	 * @param corpId
	 * @param boardId
	 * @param type 
	 * @return
	 * @Title: allPostList
	 * @Description: 所以帖子列表页面
	 * @return: Page<Map>
	 * @date 2017年11月25日 下午12:54:58
	 */
	@SuppressWarnings("rawtypes")
	public List<Map> allPostListDing1(String page, String pageSize, String token, String corpId,
			String boardId, String activeTabIndex, String treeType, String title, String type, String startDate, String endDate) {
		int pageSizeInt = Integer.parseInt(pageSize);
		int start = (Integer.parseInt(page)-1)*pageSizeInt;
		WebUser user = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT a.id,a.author,a.boardName,a.aplication_scope,a.typeName,a.title,fn_date_format(a.createdTime,'MM-dd HH:mm') createdDate,a.publishTime,fn_date_format(a.topTime,'MM-dd HH:mm') top_date,a.authorName,a.type,a.is_top, a.isCollection,");
		sql.append(" a.isAnonymity,a.isPetname,a.petname,a.attId,fn_date_format(a.lastReplyTime,'MM-dd HH:mm:ss') lastReplyDate,a.lastReplyUser,a.lastReplyUserName, ");
		sql.append(" a.viewCount,a.replyCount,a.isModerator,a.isEssence,a.publishType,case when (a.author = :userId) then 1 else 0 end as isAuthor FROM ( ");
		sql.append(" select a.id,a.boardName,a.aplication_scope,a.author,a.createdDate as createdTime,a.lastReplyDate as lastReplyTime,a.top_date as topTime, a.title, fn_date_format(a.createdDate,'yyyy-MM-dd HH:mm:ss') createdDate,fn_date_format(a.top_date,'yyyy-MM-dd HH:mm:ss') top_date, case when (os.scopeValue = :userId or :userName = 'admin' or a.author = :userId or a.isAnonymity = 0) ");
		sql.append(" then a.authorName ELSE '匿名' END AS authorName, a.type, a.is_top, a.isAnonymity,a.isPetname,a.petname, a.attId, fn_date_format(a.lastReplyDate,'yyyy-MM-dd HH:mm:ss') lastReplyDate, a.lastReplyUser,  ");
		sql.append(" a.isCollection,  CASE  WHEN (os.scopeValue != :userId OR os.scopeValue IS NULL)  AND a.is_anonymity = 1  ");
		sql.append(" THEN '匿名' ELSE  a.lastReplyUserName ");
		sql.append(" END AS lastReplyUserName, a.viewCount, a.replyCount, a.isModerator,a.typeName,a.publishTime,a.isEssence,a.publishType from ( ");
		sql.append(" select t.id AS boardid,t.name as boardName,t.aplication_scope, p.id, p.author, p.title, p.createdDate,p.publish_time as publishTime, p.top_date, x.userName as authorName, p.type, p.is_top, p.is_anonymity as isAnonymity,p.is_petname as isPetname,p.petname,case when ofs.id is null then 0 else 1 end as isCollection, p.att_id as attId, ");
		sql.append(" ps.last_reply_date as lastReplyDate, ps.last_reply_user as lastReplyUser,ps.is_anonymity, ps.lastReplyUserName, ps.view_count as viewCount, ps.reply_count as replyCount,t.is_anonymity as boardIsAnonymity, t.isModerator ,t.typeName,	p.is_essence as isEssence,p.publist_type AS publishType ");
		sql.append(" from oa_forum_post p ");
		sql.append(" left join oa_forum_scope ofs on ofs.fieldDataValue = p.is_collection and ofs.scopeValue = :userId ");
		sql.append(" inner JOIN  ");
		sql.append(" (select DISTINCT b.id, b.name,b.aplication_scope,b.is_anonymity, case when :userName = 'admin' then 1 WHEN s.id is not null then 1  else 0 end isModerator, type.name as typeName ");
		sql.append(" from oa_forum_board b ");
		sql.append(" inner join oa_forum_type type on b.forum_type = type.id and type.is_delete = 0 and type.status = 1 ");
		sql.append(" LEFT JOIN oa_forum_moderator_scope s on b.id = s.fieldDataValue and s.fieldDataTable = 'oa_forum_board' and s.scopeType = 'user' and s.scopeValue = :userId ");
		sql.append(" where b.status = '1' and b.corp_id = :corpId and b.is_delete = 0 ) t on p.board_id = t.id ");
		sql.append(" LEFT JOIN (select y.id, y.post_id, y.last_reply_date, y.last_reply_user, y.view_count, y.reply_count,");
		// 判断是否显示匿名
		sql.append(" u1.userName AS lastReplyUserName,aa.is_anonymity ");
		sql.append(" from oa_forum_post_statistics y left join ");
		sql.append(" (select u.id, u.user_name as userName from sys_user u where u.is_delete = 0 and u.corp_id = :corpId ");
		sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId)  ");
		sql.append(" u1 on y.last_reply_user = u1.id ");
		sql.append(" left join oa_forum_post aa on aa.id = y.last_reply_id and aa.corp_id = :corpId ) ");
		sql.append(" ps on p.id = ps.post_id ");
		sql.append(" left join  ");
		sql.append(" (select u.id, u.user_name as userName from sys_user u where u.corp_id = :corpId ");
		sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		sql.append(" on x.id = p.author ");
		sql.append(" where p.corp_id = :corpId and p.type = '1' and p.is_delete = 0 ");
		if("2".equals(activeTabIndex)) {//精华帖子
			sql.append(" and p.is_essence = '1' ");
		}
		if("3".equals(activeTabIndex)) {//公告帖子
			sql.append(" and p.publist_type = '2' ");
		}
		if(StringUtils.isNotBlank(boardId) && "1".equals(treeType)) {
			sql.append(" and p.board_id in ( select b.id from oa_forum_board b, oa_forum_type x where b.forum_type = x.id  ");
			sql.append("  and b.status = 1 and b.is_delete = 0 and b.corp_id = :corpId  and x.is_delete = 0   ");
			sql.append("  and x.status = 1 and x.corp_id = :corpId and b.forum_type= :boardId )");
		}else if (StringUtils.isNotBlank(boardId) ) {
			sql.append(" and p.board_id = :boardId ");
		}
		sql.append(" and (p.check_status ="+ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue()+" or p.check_status ="+ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue()+")");
		sql.append(") a LEFT JOIN (SELECT  os.scopeValue,os.fieldDataValue FROM oa_forum_moderator_scope os  WHERE os.scopeValue = :userId) os ");
		sql.append("  ON a.boardid = os.fieldDataValue  ");
		sql.append(" ) a where 1 = 1  ");
		//首页-搜索搜贴,找人,搜版块;版块导航-搜贴,找人
		if(StringUtils.isNotEmpty(title)) {
			title = SqlUtils.escapeNormalChars(title);
			if("1".equals(type)) {
				if(StringUtils.equals(title, "匿名")) {
					sql.append(" and (a.title like '%"+title+"%' or (( a.authorName like '%"+title+"%')  or  (a.author <> :userId and a.isAnonymity = 1)))");
				}else {
					sql.append(" and (a.title like '%"+title+"%' or ( a.authorName like '%"+title+"%' and a.isPetname <> 1  ) or (a.petname like '%"+title+"%')  and  (a.isAnonymity <> 1 or (a.author = :userId and a.isAnonymity = 1)  or (a.author = :userId and a.isPetname = 1)))");
				}
			}else {
				if(StringUtils.equals(title, "匿名")) {
					sql.append(" and (a.title like '%"+title+"%' or a.boardName like '%"+title+"%' or(( a.authorName like '%"+title+"%')  or  (a.author <> :userId and a.isAnonymity = 1)))");
				}else {
					sql.append(" and (a.title like '%"+title+"%' or a.boardName like '%"+title+"%' or( a.authorName like '%"+title+"%' and a.isPetname <> 1)  or (a.petname like '%"+title+"%')  and  (a.isAnonymity <> 1 or (a.author = :userId and a.isAnonymity = 1) or (a.author = :userId and a.isPetname = 1)))");
				}
			}
		}
		//起止时间查询
		if(StringUtils.isNotBlank(startDate)) {
			Date star = null;
			try {
				SimpleDateFormat  sdf1 =  new SimpleDateFormat("yyyy-MM-dd");
				star = sdf1.parse(startDate);
			}catch(Exception e) {
				e.printStackTrace();
			}
			sql.append(" and a.publishTime >= :startTime ");
			paramMap.put("startTime", star);
		}
		if(StringUtils.isNotBlank(endDate)) {
			//给结束日期加一天
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String result = "";
			try {
				Date dt = df.parse(endDate);
				result = df.format(DateUtils.addDays(dt, 1));
			} catch (Exception e) {
				e.printStackTrace();
			}
			Date end = null;
			try {
				SimpleDateFormat  sdf2 =  new SimpleDateFormat("yyyy-MM-dd");
				end = sdf2.parse(result);
			}catch(Exception e) {
				e.printStackTrace();
			}
			sql.append(" and a.publishTime <= :endTime ");
			paramMap.put("endTime", end);
		}
		//适用范围sql匹配
		String scopeSql = cmpApplyScopeService.getInScopeDataSql(userId, "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",paramMap);
		sql.append(" and " + scopeSql);
		if("1".equals(type)) {
			if("1".equals(activeTabIndex)){//最热
				sql.append(" ORDER BY a.is_top desc, a.top_date desc, a.viewCount desc,a.publishTime desc,a.id");
			}else if("0".equals(activeTabIndex)){//最新
				sql.append(" ORDER BY a.is_top desc, a.top_date desc, a.publishTime desc,a.id");
			}else if("2".equals(activeTabIndex)) {//精华
				sql.append(" ORDER BY a.is_top desc, a.top_date desc, a.publishTime desc,a.id");
			} else{
				sql.append(" ORDER BY a.is_top desc,a.top_date desc,a.publishTime desc,a.id");
			}
		}else {
			if("1".equals(activeTabIndex)){//最热
				sql.append(" ORDER BY  a.viewCount desc,a.replyCount desc,a.id");
			}else if("0".equals(activeTabIndex)){//最新
				sql.append(" ORDER BY a.publishTime desc,a.id");
			}else if("2".equals(activeTabIndex)) {//精华
				sql.append(" ORDER BY a.is_top desc,a.top_date desc,a.publishTime desc,a.id");
			} else{
				sql.append(" ORDER BY a.is_top desc,a.top_date desc,a.publishTime desc,a.id");
			}
		}
		paramMap.put("corpId", corpId);
		paramMap.put("userId", userId);
		paramMap.put("userName", user.getUserName());
		if (StringUtils.isNotBlank(boardId) ) {
			paramMap.put("boardId", boardId);
		}
		List<Map> r = super.findByListNativeQuery(sql.toString(), null, paramMap, start, pageSizeInt);
		Iterator i = r.iterator();
		List<String> l = new ArrayList<String>();
		List<String> authors = new ArrayList<String>();
		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sensitiveList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : list) {
			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}
		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		
		//获取敏感词
//		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(corpId);
//		List<String> sensitiveList = new ArrayList<String>();
//		for (ForumSensitive forumSensitive : list) {
//			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
//		}
//		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		//获取用户角色权限
		boolean flag = false;
		if(user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
			flag = true;
		}
		while (i.hasNext()) {
			Map a = (Map) i.next();
			a.put("isAdminRole", flag);
			l.add(a.get("id").toString());
			authors.add(StringUtils.null2String(a.get("author")));
			// 对每一条帖子信息的附件信息进行查询
			String attId = StringUtils.null2String(a.get("attId"));
			int imageNum = 0;
			if(attId !=null&&StringUtils.isNotBlank(attId)) {
				imageNum =  attId.split("\\|").length;
			}
			a.put("imageNum", imageNum);
			a.put("attIdJson", transformAttachmentPlanform2Dd(attId));
			//每一条帖子的发帖人图像进行查询=====userId应为每个发帖人的userID,并非当前登录人的
			String author=StringUtils.null2String(a.get("author"));
			String isAnonymity=StringUtils.null2String(a.get("isAnonymity"));//如果是匿名就不去查了 1 匿名  0  实名
			if("1".equals(isAnonymity)&&!author.equals(userId)) {
				a.put("authorName", "匿名");
			}
			if(sensitiveList!=null&&sensitiveList.size()>0) {
				a.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, a.get("title").toString(), 2, "*"));
      		}else {
      			a.put("title", a.get("title").toString());
      		}
			//敏感词替换
//			if(sensitiveList!=null&&sensitiveList.size()>0) {
//				a.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, a.get("title").toString(), 2, "*"));
//			}
			
			Map<String, String> map=new HashMap<>();
			if("0".equals(isAnonymity)) {
			map=getImage(author,  corpId,  token);
			}else {
				map.put("fileName", "");
				map.put("image", "");
			}
			a.putAll(map);
		}
		// 获取到所有的标签
		List<Map> allLabel = forumLabelService.findAllLabel(corpId);
		List<Map> r1 = null;
		if (l.size() > 0) {
			String sql2 = "select pl.post_id as postId, l.id from oa_forum_post_label pl INNER join oa_forum_label l on l.id = pl.label_id where pl.post_id in (:l) and l.is_delete = 0 order by postId, sort_no, createdDate desc, name desc ";
			Map<String, Object> paramMap2 = new HashMap<String, Object>();
			paramMap2.put("l", l);
			r1 = super.findByListNativeQuery(sql2.toString(), null, paramMap2);
		}
		for (Map p : r) {
			// 匹配帖子标签start
			if (l.size() > 0) {
				String pid = StringUtils.null2String(p.get("id"));
				List<Map> lables = new ArrayList();
				for (Map sl : allLabel) {
					Boolean f = false;
					if (!CollectionUtils.isEmpty(r1)) {
						for (Map map : r1) {
							if (StringUtils.equals(sl.get("id").toString(), StringUtils.null2String(map.get("id")))
									&& StringUtils.equals(pid, StringUtils.null2String(map.get("postId")))) {
								f = true;
							}
						}
					}
					Map swapm = new HashMap();
					swapm.put("id", sl.get("id"));
					swapm.put("name", sl.get("name"));
					swapm.put("color", sl.get("color"));
					swapm.put("status", sl.get("status"));
					if (f) {
						swapm.put("checked", true);
					} else {
						swapm.put("checked", false);
					}
					lables.add(swapm);
				}
				p.put("labels", lables);
			}
		}
		return r;
	}
	
	/**
	 * 获取帖子的回复数
	 * @param postId
	 * @return
	 */
	public Map getReplyCount(String postId) {
		String sql = "select t.reply_count replyCount from oa_forum_post_statistics t where t.post_id=:postId";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("postId", postId);
		List<Map> list = super.findByListNativeQuery(sql, null, paramMap);
		if(!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}
	
	/**
	 * 获取版块帖子的回复数
	 * @param postId
	 * @return
	 */
	public int getBoardReplyCount(String boardId) {
		String sql = "select t.id from oa_forum_post t where t.board_id=:boardId and t.post_id is not null and is_delete = '0'";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("boardId", boardId);
		List<Map> list = super.findByListNativeQuery(sql, null, paramMap);
		if(list == null){
			return 0;
		}
		return list.size();
	}
	
	/**
	 * 获取版块主帖子数
	 * @param postId
	 * @return
	 */
	public int getBoardMainCount(String boardId) {
		String sql = "select t.id from oa_forum_post t where t.board_id=:boardId and t.post_id is null and is_delete = '0'";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("boardId", boardId);
		List<Map> list = super.findByListNativeQuery(sql, null, paramMap);
		if(list == null){
			return 0;
		}
		return list.size();
	}

	public Page<Map> favoriteList(Pageable pageable, List<PropertyFilter> filter, String token, String corpId,
			String type,String appType,String title) {
		WebUser user = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		StringBuffer sql = new StringBuffer();
		Map<String, Object> values = new HashMap<String, Object>();
		sql.append(" select a.id, a.attId,a.content,a.title, a.boardId, a.author, a.postId,a.isAnonymity,a.isPetname,a.petname, fn_date_format(a.createdDate,'MM-dd HH:mm') createdDate, a.type, a.checkStatus,a.isCollection, a.entityId, a.authorName , a.boardName,a.tstatus,a.typeName,a.isCheck, a.boardStatus,a.lastReplyUser, fn_date_format(a.lastReplyDate,'yyyy-MM-dd HH:mm') lastReplyDate, a.view_count, a.reply_count ");
		sql.append(" from ( ");
		sql.append(" select t.id,t.attId,t.content, t.title, t.boardId, t.author, t.postId, t.is_anonymity as isAnonymity,t.is_petname as isPetname,t.petname,t.createdDate, t.type, t.checkStatus, t.entityId,t.isCollection, ");
		sql.append(" x.userName as authorName , b.name as boardName,type.status AS tstatus,type.name as typeName,b.is_check as isCheck, b.status AS boardStatus,s.last_reply_user as lastReplyUser, s.last_reply_date as lastReplyDate, s.view_count, s.reply_count ");
		sql.append(" from ( ");
		sql.append(" select p.id,p.att_id attId,p.content, p.title, p.board_id as boardId, p.author, p.post_id as postId, p.is_anonymity,p.is_petname,p.petname,p.createdDate, p.type,case when ofs.id is null then 0 else 1 end as isCollection, p.check_status as checkStatus, p.id as entityId ");
		sql.append(" from oa_forum_post p left join oa_forum_scope ofs on ofs.fieldDataValue = p.is_collection and ofs.scopeValue = :author");
		sql.append(" where  p.corp_id = :corpId and  p.is_delete = 0 and p.type = :type and (p.check_status = '2' or p.check_status = '4')  ");
		/*sql.append(" UNION  ");
		sql.append(" select  c.id,c.att_id attId, c.title, c.board_id as boardId, c.author, c.post_id as postId, c.createdDate, c.type, c.check_status as checkStatus, c.entity_id as entityId ");
		sql.append(" from oa_forum_check c where c.corp_id = :corpId and c.check_status = '1' and c.author = :author and c.is_delete = 0 and c.type = :type ");*/
		sql.append(" ) t ");
		sql.append(" inner join oa_forum_board b on t.boardId = b.id and b.is_delete = 0 and b.status = 1 ");
		//sql.append(" and b.status = 1 ");
		sql.append(" inner join oa_forum_type type on b.forum_type = type.id and type.is_delete = 0 ");
		sql.append(" left join  ");
		sql.append(" (select u.id, u.user_name as userName from sys_user u where ");
		//sql.append("  u.is_delete = 0 and ");
		sql.append("  u.corp_id = :corpId ");
		sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		sql.append(" on x.id = t.author ");
		sql.append(" LEFT JOIN (select y.id, y.post_id, y.last_reply_date, y.last_reply_user, y.view_count, y.reply_count, u1.userName as lastReplyUserName from oa_forum_post_statistics y left join ");
		sql.append(" (select u.id, u.user_name as userName from sys_user u where u.is_delete = 0 and u.corp_id = :corpId ");
		sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId)  ");
		if(org.ezplatform.util.GlobalConstant.isQianBase()) {
			sql.append(" u1 on y.last_reply_user = u1.id ) s on t.entityId = s.post_id limit 100");
		}else {
			sql.append(" u1 on y.last_reply_user = u1.id ) s on t.entityId = s.post_id ");
		}
		sql.append(" ) a where 1 = 1 and a.isCollection=1");
		if(StringUtils.isNotEmpty(title)) {
			sql.append(" and a.title like '%"+title+"%'");
		}
		values.put("corpId", corpId);
		values.put("author", userId);
		values.put("type", StringUtils.isNotBlank(type) ? type : POST_TYPE_NEW);
		String s = sql.toString();
		s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.createdDate desc,a.id", filter, pageable);
		Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
		List<String> bs = forumBoardService.getUserBoards();
		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sensitiveList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : list) {
			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}
		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
//		List<ForumSensitive> sensitiveList =  forumSensitiveDao.getForumSensitive(corpId);
//		List<String> sList = new ArrayList<String>();
//		for (ForumSensitive forumSensitive : sensitiveList) {
//			sList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
//		}
		//获取用户角色权限
		boolean flag = false;
		if(user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
			flag = true;
		}
		Iterator it = page.getContent().iterator();
//		Map initKeyWord = SensitiveUtils.initKeyWord(sList);
		//  我的帖子只需要查一次
		//每一条帖子的发帖人图像进行查询=====userId应为每个发帖人的userID,并非当前登录人的
		Map<String, String> map=getImage(userId,  corpId,  token);
		while (it.hasNext()) {
			Map m = (Map) it.next();
			m.put("isAdminRole", flag);
			String author=StringUtils.null2String(m.get("author"));
			if(author.equals(userId)){
				m.put("isauthor", 1);
			}else{
				m.put("isauthor", 0);
			}
			if (!CollectionUtils.isEmpty(bs) && null != m) {
				if (bs.indexOf(m.get("boardId").toString()) >= 0) {
					m.put("isModerator", 1);
				}
			}
			m.putAll(map);
			String isAnonymity=StringUtils.null2String(m.get("isAnonymity"));//如果是匿名就不去查了 1 匿名  0  实名
			if("1".equals(isAnonymity)&&!author.equals(userId)) {
				m.put("authorName", "匿名");
			}
			String isPetname=StringUtils.null2String(m.get("isPetname"));//如果是昵称 1 昵称  0  实名
			if("1".equals(isPetname)) {
				m.put("authorName", m.get("petname"));
			}
			if(sensitiveList!=null&&sensitiveList.size()>0) {
				m.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, m.get("title").toString(), 2, "*"));
     		}else {
     			m.put("title", m.get("title").toString());
     		}
			//敏感词替换
//			if(sList!=null&&sList.size()>0) {
//				m.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, m.get("title").toString(), 2, "*"));
//			}
			
			Object attIdJson;
			if (appType == "dingding") {
				attIdJson = transformAttachmentPlanform2Dd(StringUtils.null2String(m.get("attId")));
			} else {
				attIdJson = getAttachmentFile(m.get("attId"), token);
			}
			m.put("attIdJson", attIdJson);
		}
		return page;
	}

	public OperationResult favoritePost(String id, String userId, String enName, String corpId,WebUser user) {
		Map resources = new HashMap();
		ForumPost post = this.findOne(id);
		String collection = post.getIsCollection();
		
		// 检测当前用户是否已经收藏该帖子
        String sql = " select count(s.id) from oa_forum_scope s where s.scopeValue = :userId  and s.fieldDataValue = :collection and s.fieldData = 'collection' and s.scopeType = 'user' ";
        Query query = this.getEntityManager().createNativeQuery(sql).setParameter("userId", userId)
                .setParameter("collection", collection);
        String b = query.getSingleResult().toString();
        if (!b.equals("")&&Integer.parseInt(b) > 0) {
        	// 已经收藏该帖子，取消收藏
            popUserScopeUtilService.scopeDelTypeValue("oa_forum_scope", collection, "user", "oa_forum_post", userId);
            //取消收藏(主题贴)积分(不统计取消收藏自己)
            if(post.getPublistType()!=null && post.getPublistType()==1 && !user.getUserId().equals(post.getAuthor())) {
            	if(post.getAuthor()!=null) {
					if(!"1".equals(post.getAuthor().toString())) {
						Map<String,Object> userMap = userApiService.getUser(post.getAuthor(), user.getCorpId(),"", user.getJwtToken());
		    			if(userMap!=null) {
		    				forumIntegralService.savePostIntegral(post.getAuthor(), userMap.get("userName").toString(), userMap.get("loginName").toString(), "9");
		    			}
					}else {
						forumIntegralService.savePostIntegral("1", "系统管理员", "admin", "9");
					}
				}
            }
            //国际化资源
            resources.put("i18NCode", "oa.forum.cancelcollectsuc");
            return OperationResult.buildSuccessResult("取消收藏成功",resources);
        } else {
        	List<Map<Object, Object>> listMap = new ArrayList<>();
            Map<Object, Object> m = new HashMap<>();
            m.put("scopeType", "user");
            m.put("scopeValue", userId);
            m.put("scopeName", enName);
            listMap.add(m);
            popUserScopeUtilService.scopeInsert("oa_forum_scope",collection, listMap, "oa_forum_post", "collection");
            //收藏(主题贴)积分(不统计收藏自己)
            if(post.getPublistType()!=null && post.getPublistType()==1 && !user.getUserId().equals(post.getAuthor())) {
            	if(post.getAuthor()!=null) {
					if(!"1".equals(post.getAuthor().toString())) {
						Map<String,Object> userMap = userApiService.getUser(post.getAuthor(), user.getCorpId(),"", user.getJwtToken());
		    			if(userMap!=null) {
		    				forumIntegralService.savePostIntegral(post.getAuthor(), userMap.get("userName").toString(), userMap.get("loginName").toString(), "8");
		    			}
					}else {
						forumIntegralService.savePostIntegral("1", "系统管理员", "admin", "8");
					}
				}
            }
            //国际化资源
            resources.put("i18NCode", "oa.forum.collectsuc");
            return OperationResult.buildSuccessResult("收藏成功",resources);
        }
	}
	
	
	
	
	/**
	 *
	 * @Title: editSave
	 * @Description:
	 *     新增、编辑 帖子、回帖的保存。
	 * @param entity
	 * @param request 
	 * @param logCode 
	 * @return: void
	 *
	 * @date 2017年11月23日 上午11:51:38
	 *
	 */
	public OperationResult editSave(ForumPost entity, boolean isDingDing, HttpServletRequest request, String logCode) {
		Map resources = new HashMap();
		WebUser user = WebUtils.getCurrentUser();
		List<Map<String,String>> logMap = new ArrayList();
		Map<String,String> map =new HashMap();
		//是否发推送的标识(如果是编辑只改了is_copy,is_editPost,is_rePost三个字段是不需要推送的)
		boolean ifSendPost = true;
		//记录日志(只记录为编辑状态的主题帖 )
		if (StringUtils.isNoneBlank(logCode) && entity.getType() == 1) {
			if ( logCode.indexOf("02") != -1 || ( logCode.indexOf("01") != -1 && logCode.contains("draft") && StringUtils.isNotEmpty(entity.getId()) )) {
				//查询修改之前的信息
				ForumPost fp = this.findOne(entity.getId());
				map.put("fieldNameCn", "标题");
				map.put("beforeVal", fp.getTitle());
				map.put("afterVal", entity.getTitle());
				logMap.add(map);
				map = new HashMap();
				map.put("fieldNameCn", "内容");
				int beforeLength = fp.getContent().length();
				int afterLength = entity.getContent().length();
				map.put("beforeVal", fp.getContent());
				map.put("afterVal", entity.getContent());
				logMap.add(map);
				map = new HashMap();
				map.put("fieldNameCn", "图片");
				String pic = attachmentUtilsService.getAttachmentInfo(fp.getAttId(), user.getJwtToken());
				String picName = "";
				if (StringUtils.isNoneBlank(pic)) {
					pic = "["+pic+"]";
					List<Map<String,Object>> map1 = (List<Map<String, Object>>) JsonUtils.readListValue(pic);
					for (Map<String, Object> beforePic : map1) {
						if (StringUtils.isBlank(picName)) {
							picName += beforePic.get("name").toString();
						}else {
							picName += ","+beforePic.get("name").toString();
						}
						
					}
					map.put("beforeVal", picName);
				}else {
					map.put("beforeVal", "");
				}
				String pic1 = attachmentUtilsService.getAttachmentInfo(entity.getAttId(), user.getJwtToken());
				if (StringUtils.isNoneBlank(pic1)) {
					picName = "";
					pic1 = "["+pic1+"]";
					List<Map<String,Object>> map1 = (List<Map<String, Object>>) JsonUtils.readListValue(pic1);
					for (Map<String, Object> afterPic : map1) {
						if (StringUtils.isBlank(picName)) {
							picName += afterPic.get("name").toString();
						}else {
							picName += ","+afterPic.get("name").toString();
						}
						
					}
					map.put("afterVal", picName);
				}else {
					map.put("afterVal", "");
				}
				logMap.add(map);
				map = new HashMap();
				map.put("fieldNameCn", "是否匿名");
				map.put("beforeVal", fp.getIsAnonymity()==1 ? "是":"否");
				map.put("afterVal", entity.getIsAnonymity()==1 ? "是":"否");
				logMap.add(map);
				map = new HashMap();
				map.put("fieldNameCn", "允许拷贝");
				map.put("beforeVal", "1".equals(fp.getIsCopy()) ? "允许":"不允许");
				map.put("afterVal", "1".equals(entity.getIsCopy()) ? "允许":"不允许");
				logMap.add(map);
				map = new HashMap();
				map.put("fieldNameCn", "允许跟帖");
				map.put("beforeVal", "1".equals(fp.getIsRePost()) ? "允许":"不允许");
				map.put("afterVal", "1".equals(entity.getIsRePost()) ? "允许":"不允许");
				logMap.add(map);
				map = new HashMap();
				map.put("fieldNameCn", "允许修改");
				map.put("beforeVal", "1".equals(fp.getIsEditPost()) ? "允许":"不允许");
				map.put("afterVal", "1".equals(entity.getIsEditPost()) ? "允许":"不允许");
				logMap.add(map);
				String log = LogUtils.getModiInfo(logMap);
				forumIntegralService.saveModuleLog(logCode, fp.getTitle(), log); 
				//是否需要发推送(如果是编辑只改了is_copy,is_editPost,is_rePost三个字段是不需要推送的)
				if(fp.getTitle().equals(entity.getTitle()) &&  fp.getContent().equals(entity.getContent())&&pic1.equals(pic)) 
				{
					if("0".equals(fp.getCheckStatus())) {
						ForumBoard forumBoard = forumBoardService.findOne(fp.getBoardId());
						if(1 == forumBoard.getIsCheck()) {
							ifSendPost = true;
						}
					}else {
						ifSendPost = false;
					}
				}
			}else {
				forumIntegralService.saveModuleLog(logCode, entity.getTitle(), ""); 
			}
		}
		//验证该版块是否需要审核，及匿名情况
		String BoardId = "";
		if (StringUtils.null2String(entity.getBoardId()).contains(",")) {
			BoardId = entity.getBoardId().split(",")[0].toString();
		}else {
			BoardId = entity.getBoardId();
		}
		ForumBoard board = forumBoardService.findOne(BoardId);
		if (entity.getIsCopy()==null||StringUtils.isBlank(entity.getIsCopy())) {
			entity.setIsCopy("1");
		}
		if(entity.getIsEditPost()==null||StringUtils.isBlank(entity.getIsEditPost())) {
			entity.setIsEditPost("1");
		}
		if(entity.getIsRePost()==null||StringUtils.isBlank(entity.getIsRePost())) {
			entity.setIsRePost("1");
		}
		// 重新验证匿名
		if(board.getIsAnonymity() == 0){
			entity.setIsAnonymity(0);
		}
		//Map
		//Map<String, String> paramMap =new HashMap<String,String>();
		//Map<String, Object> allSearch =new HashMap<String,Object>();
		HashMap arg1 = Maps.newHashMap();
		//Map<String, String> arg1 =new HashMap<String,String>();
		boolean isCheck = board.getIsCheck() == 0?false:true;
		boolean isNew = entity.isNew();
		List<String> bs = forumBoardService.getUserBoards();
		ForumPost p = null;
		if(StringUtils.isNotBlank(entity.getId())){
			p = this.findOne(entity.getId());
			p.setRejection("");
			p.setBoardId(BoardId);
			p.setPublistType(entity.getPublistType());
		}else {
			entity.setRejection("");
		}
		if(entity.getType() == 1) {
			List<ForumSensitive> sensitiveList =  forumSensitiveDao.getForumSensitive(user.getCorpId());
			List<String> sList = new ArrayList<String>();
			for (ForumSensitive forumSensitive : sensitiveList) {
				sList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
			}
			Map initKeyWord = SensitiveUtils.initKeyWord(sList);
			if(sList!=null&&sList.size()>0) {
				entity.setTitle(SensitiveUtils.replaceSensitiveWord(initKeyWord, entity.getTitle(), 2, "*"));
				entity.setContent(SensitiveUtils.replaceSensitiveWord(initKeyWord, entity.getContent(), 2, "*"));
			}
		}
		if(!isNew){
			// 判断是否有权限编辑: 发帖人 + 版主 + admin
			if(!forumBoardService.IsModeratorOfBoard(entity.getBoardId()) &&  !this.isAuthorOfPostCheck(entity.getId()) && !SecurityUtils.isSuperAdmin(user)&& !user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue()) ){
				//国际化资源
				resources.put("i18NCode", "oa.forum.noedit");
				return OperationResult.buildFailureResult("抱歉！您没有权限进行修改",resources);
			}
		}else {
			String uuid = UUID.randomUUID().toString();   
			uuid = uuid.replace("-", "");     
			entity.setIsCollection(uuid);
		}
		//不是主贴或者是公告主贴都不许要审核
		if(entity.getType() == 2 || entity.getType() == 3 || entity.getPublistType() == 2) {
			//除了是草稿的公告帖别的都无需审核
			if(!StringUtils.null2String(entity.getCheckStatus()).equals(ForumPost.CheckStatusEnum.CHECK_STATUS_CG.getValue())) {
				entity.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
				isCheck = false;
			}
		}
		//只改了is_copy,is_editPost,is_rePost三个字段是不需要审核(草稿需要审核)
		if(!ifSendPost && !StringUtils.null2String(entity.getCheckStatus()).equals(ForumPost.CheckStatusEnum.CHECK_STATUS_CG.getValue())
				&& !StringUtils.null2String(entity.getCheckStatus()).equals(ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue())) {
			entity.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
			isCheck = false;
		}
		if (isCheck) {
			// 需要审查
			if ("0".equals(entity.getCheckStatus())) {
				entity.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_CG.getValue());
			}else {
				//如果之前是审核不通过的帖子 没有动过内容,不需要推送;
				entity.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
			}
			if (entity.getId() == null || "".equals(entity.getId())) {
				entity.setAuthor(user.getUserId());
			}
			if(entity.getIsPetname()==1) {
				Map<String, String> textParams = Maps.newHashMap();
		    	textParams.put("userId", user.getUserId());
				textParams.put("corpId", user.getCorpId());
				String jsonStr = this.restClient.get("/portal/setting/userinfo/getUserExt", user.getJwtToken(), textParams);
				Map<String, Object> result = JsonUtils.readValue(jsonStr);
				result = JsonUtils.readValue(jsonStr);
				String petName ="";
				if("0".equals(StringUtils.null2String(result.get("code")))){
					if(result.get("data")!=null) {
						Map<String, Object> userExtMap = Maps.newHashMap();
						userExtMap = (Map<String, Object>) result.get("data");
						petName = StringUtils.null2String(userExtMap.get("petName"));
					}
				}
				entity.setPetname(petName);
			}
			if (p!=null) {
				this.checkBeanCopy(p, entity);
			}else {
				try{
					p = new ForumPost();
					ConvertUtils.register(new DateConverter(null), java.util.Date.class);
					BeanUtils.copyProperties(p, entity);
				} catch(Exception e){
					LOGGER.error(e.getMessage());
					return OperationResult.buildFailureResult("后台异常");
				}
			}
			p.setPublishTime(new Date());
			p.setDataId("0");
			//审核未通过的帖子需要清空驳回理由
			entity = this.save(p);
			if (isNew) {
				forumPostStatisticsService.autoStatisticsRecord(entity);
			}
			arg1.put("id", entity.getId());
			arg1.put("checkStatus", entity.getCheckStatus());
			arg1.put("rejection", entity.getRejection());
			arg1.put("boardId", entity.getBoardId());
			arg1.put("author", entity.getCreatedBy());
			arg1.put("title", entity.getTitle());
			if (StringUtils.equals(entity.getCreatedBy(), user.getUserId())) {
				arg1.put("isAuthor", "1");
			}else {
				arg1.put("isAuthor", "0");
			}
			
			if (!CollectionUtils.isEmpty(bs) && null != entity) {
				if (bs.indexOf(entity.getBoardId()) >= 0) {
					arg1.put("isModerator", "1");
				}else {
					arg1.put("isModerator", "0");
				}
			}else {
				arg1.put("isModerator", "0");
			}
		} else {
			// 不需要审查
			if ("0".equals(entity.getCheckStatus())) {
				entity.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_CG.getValue());
			}else {
				entity.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
			}
			if(entity.getIsPetname()==1) {
				Map<String, String> textParams = Maps.newHashMap();
		    	textParams.put("userId", user.getUserId());
				textParams.put("corpId", user.getCorpId());
				String jsonStr = this.restClient.get("/portal/setting/userinfo/getUserExt", user.getJwtToken(), textParams);
				Map<String, Object> result = JsonUtils.readValue(jsonStr);
				result = JsonUtils.readValue(jsonStr);
				String petName ="";
				if("0".equals(StringUtils.null2String(result.get("code")))){
					if(result.get("data")!=null) {
						Map<String, Object> userExtMap = Maps.newHashMap();
						userExtMap = (Map<String, Object>) result.get("data");
						petName = StringUtils.null2String(userExtMap.get("petName"));
					}
				}
				entity.setPetname(petName);
			}
			entity.setAuthor(user.getUserId());
			if (null == p) {
				try{
					p = new ForumPost();
					ConvertUtils.register(new DateConverter(null), java.util.Date.class);
					BeanUtils.copyProperties(p, entity);
				} catch(Exception e){
					LOGGER.error(e.getMessage());
					return OperationResult.buildFailureResult("后台异常");
				}
			} else {
				this.checkBeanCopy(p, entity);
			}
			p.setPublishTime(new Date());
			if (p.getId()==null||StringUtils.isBlank(p.getId())) {
				String uuId = UUID.randomUUID().toString();   
				uuId = uuId.replace("-", "");     
				p.setId(uuId);
			}
			p.setDataId("0");
			p = this.save(p);
			//保存之后进行全文检索的操作
			if (ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue().equals(p.getCheckStatus())&&p.getType()==1) {
				this.AllSearch(p, user, isNew,"0");
			}
			arg1.put("id", p.getId());
			arg1.put("title", p.getTitle());
			arg1.put("checkStatus", p.getCheckStatus());
			arg1.put("author", p.getCreatedBy());
			arg1.put("boardId", p.getBoardId());
			if(StringUtils.equals(p.getCreatedBy(), user.getUserId())) {
				arg1.put("isAuthor","1" );
			}else {
				arg1.put("isAuthor", "0");
			}
			arg1.put("rejection", p.getRejection());
			if (!CollectionUtils.isEmpty(bs) && null != p) {
				if (bs.indexOf(p.getBoardId()) >= 0) {
					arg1.put("isModerator", "1");
				}else {
					arg1.put("isModerator", "0");
				}
			}else {
				arg1.put("isModerator", "0");
			}
			if(isNew) {
				forumPostStatisticsService.autoStatisticsRecord(p);
			}
			
		}
		/****************************** 论坛推送开始*******************************/
		if(StringUtils.equals(arg1.get("checkStatus").toString(), ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue()) &&ifSendPost) {
			try {
				String sendPath = ForumPostSendUtils.getSysImType(user.getCorpId(), user.getJwtToken());
				String ids = "";
				//所属人信息
				//Map<String,Object> userMap = userApiService.getUser(user.getUserId(),user.getCorpId(),"",user.getJwtToken());
				arg1.put("userName", StringUtils.null2String(user.getUserName()));
				 if (p.getIsAnonymity() == 1) {
					 arg1.put("userName", "匿名");
				} else {
					if (StringUtils.equals(StringUtils.null2String(p.getAuthor()), "1")) {
						arg1.put("userName", "系统管理员");
					} else {
						//Map<String, Object> us = userApiService.getUser(p.getAuthor(), user.getCorpId(), "", user.getJwtToken());
						String userName = cmpPopUserOrgName.getUserNameById(StringUtils.null2String(p.getAuthor()));
						if (userName != null) {
							arg1.put("userName", userName);
						}else {
							arg1.put("userName","用户不存在");
						}
					}
				}
				String getScopeTypeValue = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope", "oa_forum_board", "id", StringUtils.null2String(arg1.get("boardId")));
				if (StringUtils.isNotBlank(getScopeTypeValue)) {
	            	String[] idArr = getScopeTypeValue.split(",");
	            	for (String id : idArr) {
	                	ids += id.split("SCOPE")[1] + ",";
	            	}
	        	}
				//获取后台系统推送方式配置
				String reminderAction = "" ;
				Map<String, Object> appInfo = configService.getAppInfoByAppCode("stdForum",user.getCorpId(),user.getJwtToken());
		        if(MapUtils.isNotEmpty(appInfo)) {
		        	reminderAction = StringUtils.null2String(appInfo.get("reminderAction"));
		        }
				arg1.put("sendPath", sendPath);
				if(StringUtils.isNotEmpty(reminderAction)) {
					if(reminderAction.contains("mobile")) {
						ForumPostSendUtils.sendMsg(mobileMessageService, request, user.getCorpId(), ids,"",arg1);
					}
				}
				Map<String,String> paramMaps = new HashMap<>();
				paramMaps.put("userId",user.getUserId());
				paramMaps.put("corpId",user.getCorpId());
				paramMaps.put("token",user.getJwtToken());
				paramMaps.put("msgTitle","新发表的帖子等待您的审核，请尽快完成！");
				paramMaps.put("dataId", entity.getId());
				paramMaps.put("msgContent","新发表的帖子等待您的审核，请尽快完成！");
				paramMaps.put("url",ForumPostSendUtils.URL);
				paramMaps.put("PostId",entity.getId());
				paramMaps.put("pagetype","myCheck");
				//msgType = 2 为代办
				paramMaps.put("msgType","1");
				paramMaps.put("msgReceiver",ids);
				paramMaps.put("id",arg1.get("id").toString());
				paramMaps.put("checkStatus",arg1.get("checkStatus").toString());
				ForumPostSendUtils.sendMsgToOffice(paramMaps);
				if(StringUtils.isNotEmpty(reminderAction)) {
					if(reminderAction.contains("sms")) {
						Map<String, String> paramMapSms = new HashMap<>();
						paramMapSms.put("sender", user.getUserId());
						paramMapSms.put("senderOrg", StringUtils.null2String(user.getOrgId()));
						paramMapSms.put("receiverIds", ids);
			            paramMapSms.put("systemName", "本系统");
			            paramMapSms.put("appCode", "stdForum");
			            paramMapSms.put("sendContent", "新发表的帖子等待您的审核，请尽快完成! ");
			            paramMapSms.put("userId", user.getUserId());
		                paramMapSms.put("corpId", user.getCorpId());
		                paramMapSms.put("token", user.getJwtToken());
		                paramMapSms.put("smsPath", "1");
		                paramMapSms.put("remindStyle", "");
		            	List<Map<String, Object>> userMapList =  userApiService.getUserList(ids, user.getCorpId(), "", user.getJwtToken());
		            	ForumPostSendUtils.sendSms(paramMapSms,userMapList);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		/****************************** 论坛推送结束*******************************/
		if(StringUtils.equals(p.getCheckStatus(), ForumPost.CheckStatusEnum.CHECK_STATUS_CG.getValue())) {
			//国际化资源
			arg1.put("i18NCode", "oa.forum.savesuccess");
			return OperationResult.buildSuccessResult("保存成功", arg1);
		}
		if(p.getType() == 2) {
			//评论他人（主题）帖增加积分 6-评论
			if(p.getPublistType()!=null && p.getPublistType()==1 && request.getAttribute("mainPostAuthor")!=null && !user.getUserId().equals(request.getAttribute("mainPostAuthor").toString())) {
				forumIntegralService.savePostIntegral(user.getUserId(),user.getCnName(),user.getUserName(),"6");
			}
			//国际化资源
			arg1.put("i18NCode", "oa.forum.sendsuc");
			return OperationResult.buildSuccessResult("发送成功", arg1);
		}
		//发帖（主题）(草稿箱发帖)增加积分 0-发帖
		if(p.getType() == 1 && (entity.getId()==null || "forum:draft:01".equals(logCode)) && "4".equals(p.getCheckStatus()) && p.getPublistType()!=null && p.getPublistType()==1) {
			forumIntegralService.savePostIntegral(user.getUserId(),user.getCnName(),user.getUserName(),"0");
		}
		//国际化资源
		if (isCheck) {
			arg1.put("i18NCode", "oa.forum.checkposton");
			return OperationResult.buildSuccessResult("帖子已发布，请等待版主审核", arg1);
		}else {
			arg1.put("i18NCode", "oa.forum.poston");
			return OperationResult.buildSuccessResult("发布成功", arg1);
		}
	}
	
	
	
	
	/**
	 * 
	 * @Title: checkBeanCopy
	 * @Description:
	 *     审核帖子过程中的对象拷贝
	 * @param p
	 * @param c 
	 * @return: void
	 *
	 * @date 2017年11月28日 下午2:38:02
	 *
	 */
	public void checkBeanCopy(ForumPost p, ForumPost c){
		p.setContent(c.getContent());
		p.setTitle(c.getTitle());
		p.setAttId(c.getAttId());
		p.setLastModifiedBy(c.getCreatedBy());
		p.setLastModifiedDate(c.getLastModifiedDate());
		p.setLastModifiedOrg(c.getLastModifiedOrg());
		p.setIsAnonymity(c.getIsAnonymity());
		p.setCheckStatus(c.getCheckStatus());
		p.setIsCopy(c.getIsCopy());
		p.setIsRePost(c.getIsRePost());
		p.setIsEditPost(c.getIsEditPost());
	}

	public OperationResult sendPost(String id, WebUser user, HttpServletRequest request) {
		ForumPost forumPost = this.findOne(id);
		ForumBoard board = forumBoardService.findOne(forumPost.getBoardId());
		boolean isCheck = board.getIsCheck() == 0?false:true;
		if(isCheck) {
			forumPost.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
		}else {
			forumPost.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		}
		HashMap arg1 = Maps.newHashMap();
		arg1.put("id", forumPost.getId());
		forumPost.setPublishTime(new Date());
		/*String uuid = UuidUtils.UUID();
		forumPost.setDataId(uuid);*/
		forumPost =  this.save(forumPost);
		logService.saveModuleLog("forum:draft:01", forumPost.getTitle(), ""); 
		if(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue().equals(forumPost.getCheckStatus())) {
			this.AllSearch(forumPost, WebUtils.getCurrentUser(), true,"0");
		}
			/****************************** 论坛推送开始*******************************/
			if(StringUtils.equals(forumPost.getCheckStatus(), ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue())) {
				try {
					Map<String,String> sendMap = new HashMap<>();
					List<String> bs = forumBoardService.getUserBoards();
					sendMap.put("id", forumPost.getId());
					sendMap.put("title", forumPost.getTitle());
					sendMap.put("checkStatus", forumPost.getCheckStatus());
					sendMap.put("author", forumPost.getCreatedBy());
					sendMap.put("boardId", forumPost.getBoardId());
					sendMap.put("rejection", forumPost.getRejection());
					//推送方式
					String sendPath = ForumPostSendUtils.getSysImType(user.getCorpId(), user.getJwtToken());
					if(StringUtils.equals(forumPost.getCreatedBy(), user.getUserId())) {
						sendMap.put("isAuthor","1" );
					}else {
						sendMap.put("isAuthor", "0");
					}
					if (!CollectionUtils.isEmpty(bs) && null != forumPost) {
						if (bs.indexOf(forumPost.getBoardId()) >= 0) {
							sendMap.put("isModerator", "1");
						}else {
							sendMap.put("isModerator", "0");
						}
					}else {
						sendMap.put("isModerator", "0");
					}
					 String ids = "";
					//获取后台系统推送方式配置
					String reminderAction = "" ;
					Map<String, Object> appInfo = configService.getAppInfoByAppCode("stdForum",user.getCorpId(),user.getJwtToken());
			        if(MapUtils.isNotEmpty(appInfo)) {
			        	reminderAction = StringUtils.null2String(appInfo.get("reminderAction"));
			        }
					//所属人信息
					Map<String,Object> userMap =
							userApiService.getUser(user.getUserId(),user.getCorpId(),"",user.getJwtToken());
					sendMap.put("userName", StringUtils.null2String(userMap.get("userName")));
					 if (forumPost.getIsAnonymity() == 1) {
						 sendMap.put("userName", "匿名");
						} else {
							if (StringUtils.equals(StringUtils.null2String(forumPost.getAuthor()), "1")) {
								sendMap.put("userName", "系统管理员");
							} else {
								Map<String, Object> us = userApiService.getUser(forumPost.getAuthor(), user.getCorpId(), "", user.getJwtToken());
								if (us != null) {
									sendMap.put("userName", us.get("userName").toString());
								}else {
									sendMap.put("userName","用户不存在");
								}
							}
						}
					String getScopeTypeValue = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope", "oa_forum_board", "id", StringUtils.null2String(forumPost.getBoardId()));
					if (StringUtils.isNotBlank(getScopeTypeValue)) {
		            	String[] idArr = getScopeTypeValue.split(",");
		            	for (String id1 : idArr) {
		                	ids += id1.split("SCOPE")[1] + ",";
		            	}
		        	}
					sendMap.put("sendPath", sendPath);
					if(StringUtils.isNotEmpty(reminderAction)) {
						if(reminderAction.contains("mobile")) {
							ForumPostSendUtils.sendMsg(mobileMessageService, request, user.getCorpId(), ids,"",sendMap);
						}
					}
					Map<String,String> paramMaps = new HashMap<>();
					paramMaps.put("userId",user.getUserId());
					paramMaps.put("corpId",user.getCorpId());
					paramMaps.put("token",user.getJwtToken());
					paramMaps.put("msgTitle","新发表的帖子等待您的审核，请尽快完成！");
					paramMaps.put("dataId", forumPost.getId());
					paramMaps.put("msgContent","新发表的帖子等待您的审核，请尽快完成！");
					paramMaps.put("url",ForumPostSendUtils.URL);
					paramMaps.put("PostId",forumPost.getId());
					paramMaps.put("msgReceiver",ids);
					//msgType = 2 为代办
					paramMaps.put("msgType","2");
					paramMaps.put("id",forumPost.getId());
					paramMaps.put("checkStatus",forumPost.getCheckStatus());
					ForumPostSendUtils.sendMsgToOffice(paramMaps);
					if(StringUtils.isNotEmpty(reminderAction)) {
						if(reminderAction.contains("sms")) {
							Map<String, String> paramMapSms = new HashMap<>();
							paramMapSms.put("sender", user.getUserId());
							paramMapSms.put("senderOrg", StringUtils.null2String(userMap.get("orgId")));
							paramMapSms.put("receiverIds", ids);
				            paramMapSms.put("systemName", "本系统");
				            paramMapSms.put("appCode", "stdForum");
				            paramMapSms.put("sendContent", "新发表的帖子等待您的审核，请尽快完成! ");
				            paramMapSms.put("userId", user.getUserId());
			                paramMapSms.put("corpId", user.getCorpId());
			                paramMapSms.put("token", user.getJwtToken());
			                paramMapSms.put("smsPath", "1");
			                paramMapSms.put("remindStyle", "");
			            	List<Map<String, Object>> userMapList =  userApiService.getUserList(ids, user.getCorpId(), "", user.getJwtToken());
			            	ForumPostSendUtils.sendSms(paramMapSms,userMapList);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			/****************************** 论坛推送结束*******************************/
		return OperationResult.buildSuccessResult("发表成功", arg1);
	}
	
	/**
     * 
     * @Title: list
     * @Description:
     * 		待审核列表    
     * @param pageable
     * @param filter
     * @param token
	 * @param corpId 
     * @return 
     * @return: Page<Map>
     *
     * @date 2017年11月25日 下午4:00:27
     *
     */
	public Page<Map> checkList(Pageable pageable, List<PropertyFilter> filter, String token,String appType,String title, String corpId) {
		WebUser user = WebUtils.getCurrentUser();
		StringBuffer s0 = new StringBuffer();
		Map<String, Object> values = new HashMap<String, Object>();
		s0.append(" select a.id,a.attId, a.title, a.author,a.isAnonymity,a.isPetname,a.petname, a.type,a.postId,a.checkStatus,a.boardName,a.aplication_scope,a.typeName,fn_date_format(a.createdDate,'MM-dd HH:mm') createdDate,fn_date_format(a.publishTime,'MM-dd HH:mm') publishTime,a.content, a.authorName from ( ");
		s0.append(" select t.id,t.attId,t.title,t.author,t.isAnonymity,t.isPetname,t.petname,t.type,t.postId,t.checkStatus,t.boardName,t.aplication_scope,t.typeName,t.createdDate,t.publishTime,t.content, x.userName as authorName from ( ");
		s0.append(" select c.id,c.att_id attId, c.title, c.author,c.is_anonymity as isAnonymity,c.is_petname as isPetname,c.petname,c.type, c.post_id as postId, c.check_status as checkStatus, b.name as boardName,b.aplication_scope,type.name as typeName, c.createdDate,c.publish_time as publishTime, c.content ");
		s0.append(" FROM oa_forum_post c, oa_forum_board b, oa_forum_type type");
		if ("admin".equals(user.getUserName())||user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())) {
			s0.append(" where ");
		}else {
			s0.append(" ,oa_forum_moderator_scope s where s.fieldDataValue = b.id and s.scopeValue = :userId and s.fieldDataTable = 'oa_forum_board' and s.scopeType = 'user' and ");
		}
		s0.append(" b.id = c.board_id and c.corp_id = :corpId and c.check_status = :status and c.is_delete = 0 and c.type = "+POST_TYPE_NEW+" ");
		s0.append("  and b.is_delete = 0 and b.forum_type = type.id and type.is_delete = 0 and b.status = 1 ");
		s0.append(" ) t ");
		s0.append(" left join  ");
		s0.append(" (select u.id, u.user_name as userName from sys_user u where u.corp_id = :corpId ");
		s0.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		s0.append(" on x.id = t.author ");
		s0.append(" ) a where  ");
		String scopeSql = cmpApplyScopeService.getInScopeDataSql(user.getUserId(), "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",values);
		s0.append(scopeSql);
		if (StringUtils.isNotEmpty(title)) {
			s0.append(" and a.title like '%"+title+"%'");
		}
		if(!"admin".equals(user.getUserName())&&!user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())) {
			values.put("userId", user.getUserId());
		}
		values.put("corpId", user.getCorpId());
		values.put("status", ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
		List<String> ids =new ArrayList<>();
		String s = s0.toString();
		
		s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.createdDate desc ", filter, pageable);
		Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
		Iterator it = page.getContent().iterator();
		while (it.hasNext()) {
			Map a = (Map) it.next();
			//获取用户角色权限
			boolean flag = false;
			if (user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
				a.put("isAdminRole", true);
			}
			a.put("title", a.get("title").toString());
			//每一条帖子的发帖人图像进行查询=====userId应为每个发帖人的userID,并非当前登录人的
			String author=StringUtils.null2String(a.get("author"));
			String isAnonymity=StringUtils.null2String(a.get("isAnonymity"));//如果是匿名就不去查了 1 匿名  0  实名
			if (StringUtils.equals(isAnonymity, "1")) {
				if (StringUtils.equals(user.getUserId(), StringUtils.null2String(author))) {
					// 版主、管理员、自己查看的时候显示真实姓名+匿名标注
					if (StringUtils.equals(StringUtils.null2String(author), "1")) {
						a.put("authorName", "系统管理员(匿名)");
					} else {
						Map<String, Object> us = userApiService.getUser(author, user.getCorpId(), "", token);
						if (us != null) {
							a.put("authorName", us.get("userName") + "(匿名)");
						}
					}
				} else {
					a.put("authorName", "匿名");
				}
			} else {
				String isPetname=StringUtils.null2String(a.get("isPetname"));//如果是昵称 1 昵称  0  实名
				if (StringUtils.equals(isPetname, "1")) {
					String petname = a.get("petname")+"";
					/*if(!"".equals(petname) && petname.length()>3) {
						petname = petname.substring(0, 3);
					}*/
					if (StringUtils.equals(user.getUserId(), StringUtils.null2String(author))) {
						// 版主、管理员、自己查看的时候显示真实姓名+昵称
						if (StringUtils.equals(StringUtils.null2String(author), "1")) {
							a.put("authorName", "系统管理员("+petname+")");
						} else {
							Map<String, Object> us = userApiService.getUser(author, user.getCorpId(), "", token);
							if (us != null) {
								a.put("authorName", us.get("userName") + "("+petname+")");
							}
						}
					} else {
						a.put("authorName", petname);
					}
				}else {
					if (StringUtils.equals(StringUtils.null2String(author), "1")) {
						a.put("authorName", "系统管理员");
					} else {
						Map<String, Object> us = userApiService.getUser(author, user.getCorpId(), "", token);
						if (us != null) {
							a.put("authorName", us.get("userName"));
						}
					}
				}
			}
		}
		return page;
	}

	/**
	 * 
	 * @Title: checkPostList
	 * @Description:
	 *     审核帖子
	 * @param ids
	 * @param type 
	 * @param request 
	 * @return 
	 * @return: OperationResult
	 *
	 * @date 2017年11月25日 下午4:16:01
	 *
	 */
	public OperationResult checkPostInfo(String[] ids, String type,String rejection, HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		List<ForumPost> checks = forumPostDao.getCheckByIdAnDStatus(Arrays.asList(ids), ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
		int oc = 0;
		List<String> fids = new ArrayList<String>();
		if(checks != null && !checks.isEmpty()){
			StringBuffer s1 = new StringBuffer();
			s1.append(" select s.fieldDataValue from oa_forum_moderator_scope s where s.fieldDataTable = 'oa_forum_board' and s.scopeType = 'user'");
			if(!user.getRoleCodes().contains("appAdminRole")) {
				s1.append(" and s.scopeValue = '" + user.getUserId() + "'");
			}
			List<String> bs = this.getEntityManager().createNativeQuery(s1.toString()).getResultList();
			if((bs != null && !bs.isEmpty()) || !user.getRoleCodes().contains("appAdminRole")){
				for(ForumPost c : checks){
					if(bs.indexOf(c.getBoardId()) >=0 || user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue()) || "1".equals(user.getUserId())){
						try {
							ForumBoard board = forumBoardService.findOne(c.getBoardId());
							if(StringUtils.equals(type, ForumPost.CheckStatusEnum.CHECK_STATUS_SHBTG.getValue())) {
								c.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_SHBTG.getValue());
							}else {
								c.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
							}
							
							// 此处需要判断，这条审核记录为  再次编辑产生的 or 新建产生的
							// 根据id进行区分。 新建产生的 ----- 审核过程中，check表先产生一条记录， 审核通过后，post表产生一条新的记录，同时删除check表记录
							// 编辑产生的 ----- 审核过程中，check表先产生一条记录， 审核通过后，post表产生一条和check.entity_id相同的记录，然后删除check表中的记录。注意：此处的check.entity_id为产生该check记录中保存进去的
							// 当check表中存在 entity_id 的时候，则认为该check记录为，帖子审核通过后，编辑产生的待审核记录。否则为新建产生
							
							ForumPost p = new ForumPost();
							ConvertUtils.register(new DateConverter(null), java.util.Date.class);
							BeanUtils.copyProperties(p, c);
							if(p.getId()==null||StringUtils.isBlank(p.getId())) {
								p.setId(UuidUtils.UUID());
							}
							p.setRejection(rejection);
							p.setPublishTime(new Date());
							p = this.save(p);
							//(审核)发帖（主题）增加积分 0-发帖
							if("2".equals(p.getCheckStatus()) && p.getPublistType()!=null && p.getPublistType()==1) {
								if(p.getAuthor()!=null) {
									if(!"1".equals(p.getAuthor().toString())) {
										Map<String,Object> userMap = userApiService.getUser(p.getAuthor(), user.getCorpId(),"", user.getJwtToken());
										if(userMap!=null) {
											forumIntegralService.savePostIntegral(p.getAuthor(),userMap.get("userName").toString(), userMap.get("loginName").toString(),"0");
										}
									}else {
										forumIntegralService.savePostIntegral("1", "系统管理员", "admin", "0");
									}
								}
							}
							if(p.getCheckStatus().equals(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue())) {
								this.AllSearch(p,user,true,"0");
							}
							this.postPushMsg(p,user);
							Map<String, Object> userCheck = userApiService.getUser(p.getAuthor(), user.getCorpId(), "", user.getJwtToken());
							/****************************** 论坛推送开始*******************************/
							if(StringUtils.equals(p.getCheckStatus(), ForumPost.CheckStatusEnum.CHECK_STATUS_SHBTG.getValue())) {
								Map<String,String> mapList = new HashMap<>();
									try {
										List<String> bs1 = forumBoardService.getUserBoards();
										String sendPath = ForumPostSendUtils.getSysImType(user.getCorpId(), user.getJwtToken());
										if(StringUtils.equals(p.getCreatedBy(), user.getUserId())) {
											mapList.put("isAuthor", "1" );
										}else {
											mapList.put("isAuthor", "0");
										}
										if (!CollectionUtils.isEmpty(bs1) && null != p) {
											if (bs1.indexOf(p.getBoardId()) >= 0) {
												mapList.put("isModerator", "1");
											}else {
												mapList.put("isModerator", "0");
											}
										}else {
											mapList.put("isModerator", "0");
										}
										String receiverIds = "";
										String getScopeTypeValue = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope", "oa_forum_board", "id", StringUtils.null2String(c.getBoardId()));
										if (StringUtils.isNotBlank(getScopeTypeValue)) {
							            	String[] idArr = getScopeTypeValue.split(",");
							            	for (String id : idArr) {
							            		receiverIds += id.split("SCOPE")[1] + ",";
							            	}
							        	}
										//所属人信息
										Map<String,Object> userMap = userApiService.getUser(user.getUserId(),user.getCorpId(),"",user.getJwtToken());
										if(userMap != null) {
											mapList.put("userName", StringUtils.null2String(userMap.get("userName")));
										}
										if (p.getIsAnonymity() == 1) {
											 mapList.put("userName", "匿名");
										}else {
									        if (StringUtils.equals(StringUtils.null2String(p.getAuthor()), "1")) {
												mapList.put("userName", "系统管理员");
											} else {
												Map<String, Object> us = userApiService.getUser(p.getAuthor(), user.getCorpId(), "", user.getJwtToken());
												if (us != null) {
													mapList.put("userName", us.get("userName").toString());
												}else {
													mapList.put("userName","用户不存在");
												}
											}
										}
										//获取后台系统推送方式配置
										String reminderAction = "" ;
										Map<String, Object> appInfo = configService.getAppInfoByAppCode("stdForum",user.getCorpId(),user.getJwtToken());
								        if(MapUtils.isNotEmpty(appInfo)) {
								        	reminderAction = StringUtils.null2String(appInfo.get("reminderAction"));
								        }
										mapList.put("sendPath", sendPath);
										mapList.put("id", p.getId());
										mapList.put("title", p.getTitle());
										mapList.put("checkStatus", p.getCheckStatus());
										mapList.put("author", p.getCreatedBy());
										mapList.put("boardId", p.getBoardId());
										mapList.put("rejection", p.getRejection());
										if(StringUtils.isNotEmpty(reminderAction)) {
											if(reminderAction.contains("mobile")) {
												ForumPostSendUtils.sendMsg(mobileMessageService, request, user.getCorpId(), p.getAuthor(),"",mapList);
											}
										}
										//ForumPostSendUtils.sendMsg(mobileMessageService, request, user.getCorpId(), p.getAuthor(),"",mapList);
										Map<String,String> paramMaps = new HashMap<>();
										paramMaps.put("userId",user.getUserId());
										paramMaps.put("corpId",user.getCorpId());
										paramMaps.put("token",user.getJwtToken());
										paramMaps.put("msgTitle","您发表的帖子审核未通过："+p.getTitle());
										paramMaps.put("dataId", p.getId());
										paramMaps.put("msgContent","您发表的帖子审核未通过："+p.getTitle());
										paramMaps.put("url",ForumPostSendUtils.URL);
										paramMaps.put("msgType","1");
										paramMaps.put("PostId",p.getId());
										paramMaps.put("msgReceiver",p.getAuthor());
										paramMaps.put("msgSenderType", "11");
										paramMaps.put("msgSender", "-1");
										paramMaps.put("id",p.getId());
										paramMaps.put("checkStatus",p.getCheckStatus());
										if(userCheck != null) {
											if(!StringUtils.equals((String)userCheck.get("userStatus"), "offDuty")) {
												ForumPostSendUtils.sendMsgToOffice(paramMaps);
											}
										}
										if(StringUtils.isNotEmpty(reminderAction)) {
											if(reminderAction.contains("sms")) {
												Map<String, String> paramMapSms = new HashMap<>();
												paramMapSms.put("sender", user.getUserId());
												paramMapSms.put("senderOrg", StringUtils.null2String(userMap.get("orgId")));
												paramMapSms.put("receiverIds", receiverIds);
									            paramMapSms.put("systemName", "本系统");
									            paramMapSms.put("appCode", "stdForum");
									            paramMapSms.put("sendContent", "您发表的帖子审核未通过："+p.getTitle());
									            paramMapSms.put("userId", user.getUserId());
								                paramMapSms.put("corpId", user.getCorpId());
								                paramMapSms.put("token", user.getJwtToken());
								                paramMapSms.put("smsPath", "1");
								                paramMapSms.put("remindStyle", "");
								            	List<Map<String, Object>> userMapList =  userApiService.getUserList(receiverIds, user.getCorpId(), "", user.getJwtToken());
												ForumPostSendUtils.sendSms(paramMapSms,userMapList);
											}
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
							}
							/****************************** 论坛推送结束*******************************/
							oc++;
							forumPostStatisticsService.autoStatisticsRecord(p);
						} catch (IllegalAccessException  e) {
							 LOGGER.error(e.getMessage());
							 fids.add(c.getId());
						} catch (InvocationTargetException e){
							LOGGER.error(e.getMessage());
							fids.add(c.getId());
						}
					} else {
						fids.add(c.getId());
					}
				}
				if(ids.length ==1 ){
					Map resources = new HashMap();
					//国际化资源
					resources.put("i18NCode", "oa.forum.reviewtips4");
					if(oc == ids.length){
						return OperationResult.buildSuccessResult("审核成功",resources);
					} else {
						return OperationResult.buildFailureResult("审核失败", fids);
					}
				} else {
					Map resources = new HashMap();
					//国际化资源
					resources.put("i18NCode", "oa.forum.reviewtips4");
					if(oc == ids.length){
						return OperationResult.buildSuccessResult("审核成功",resources);
					} else {
						return OperationResult.buildWarningResult("批量审核操作已处理. 成功:" + oc + "条,失败:" + (ids.length - oc) + "条", fids);
					}
				}
			} else {
				Map resources = new HashMap();
				//国际化资源
				resources.put("i18NCode", "oa.forum.nooperation");
				return OperationResult.buildFailureResult("抱歉！您不是版主，不能进行操作",resources);
			}
		}
		if(ids!=null&&ids.length>0) {
			Map resources = new HashMap();
			//国际化资源
			resources.put("i18NCode", "oa.forum.reviewtips6");
			return  OperationResult.buildFailureResult("抱歉！该数据已被删除或者已被处理",resources);
		}else {
			Map resources = new HashMap();
			//国际化资源
			resources.put("i18NCode", "oa.forum.selectrecord");
			return  OperationResult.buildFailureResult("请选择记录",resources);
		}
		
	}
	

	
    public void AllSearch(ForumPost p, WebUser user, boolean isNew, String count) {
		Map<String, String> paramMap =new HashMap<String,String>();
		Map<String, Object> allSearch =new HashMap<String,Object>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		allSearch.put("id", p.getId());
		Map boardName = forumBoardService.getForumBoard(p.getBoardId());
		allSearch.put("createdBy", user.getUserId());
		allSearch.put("createdDate", sdf.format(p.getCreatedDate()));
		allSearch.put("modelCode", modelCode);
		allSearch.put("boardName", boardName.get("text").toString());
		allSearch.put("title",StringUtils.null2String(p.getTitle()));
		allSearch.put("content", StringUtils.null2String(p.getContent()));
		if (p.getIsAnonymity() == 1) {
			if (StringUtils.equals(user.getUserId(), StringUtils.null2String(p.getAuthor()))) {
				// 版主、管理员、自己查看的时候显示真实姓名+匿名标注
				if (StringUtils.equals(StringUtils.null2String(p.getAuthor()), "1")) {
					allSearch.put("createdName", "匿名");
				} else {
					Map<String, Object> us = userApiService.getUser(p.getAuthor(), user.getCorpId(), "", user.getJwtToken());
					if (us != null) {
						allSearch.put("createdName", "匿名");
					}
				}
			} else {
				allSearch.put("createdName", "匿名");
			}
		} else {
			if (StringUtils.equals(StringUtils.null2String(p.getAuthor()), "1")) {
				allSearch.put("createdName", "系统管理员");
			} else {
				Map<String, Object> us = userApiService.getUser(p.getAuthor(), user.getCorpId(), "", user.getJwtToken());
				if (us != null) {
					allSearch.put("createdName", us.get("userName"));
				}
			}
		}
		allSearch.put("attId", p.getAttId());
		allSearch.put("viewCounts", count);
		allSearch.put("corpId", user.getCorpId());
		allSearch.put("openUrl", "forumView");
		if(p.getAttId()!=null&&StringUtils.isNotBlank(p.getAttId())) {
			String id = p.getAttId();
			String[] attId = id.split("\\|");
			String dataInitList = attchService.getAttachmentInfo(attId[0],user.getJwtToken());
			Map<String, Object> map = JsonUtils.readValue(dataInitList);
			if(map.get("url")!=null&&StringUtils.isNotBlank(map.get("url").toString())) {
				allSearch.put("titleImagerUrl", map.get("url").toString().replace("download", "image"));
			}else {
				allSearch.put("titleImagerUrl", "");
			}
			
		}
		String viewCounts = "0";
		if(isNew) {
			allSearch.put("status", "2");//新建
		}else {
			allSearch.put("status", "1");//编辑
			viewCounts = forumPostStatisticsService.getCounts(p.getId(),user.getCorpId());
		}
		/*String json="[{\"createdBy\":\""+user.getUserId()+"\",\"createdDate\":\""+user.getUserId()+"\"," +
				"\"createdName\":\""+user.getCnName()+"\",\"modelCode\":\""+modelCode+"\",\"boardName\":\""+boardName.get("text").toString()+"\","
						+ "\"title\":\""+entity.getTitle()+"\",\"content\":\""+entity.getContent()+"\",\"attId\":\""+entity.getAttId()+"\","
								+ "\"viewCounts\":\"0\"}]";*/
		restClient.post("/integ/fullsearch/searchServer/saveServerInfo", user.getJwtToken(), paramMap, JSON.toJSONString(allSearch));
	}

	
	
	
	/**
	 * 移动端移动帖子版块
	 * @param postId
	 * @param oldBoardId
	 * @param newBoardId
	 * @return
	 */
	public OperationResult changePostBoard(String postId,String oldBoardId,String newBoardId,HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		List<String> list = new ArrayList<>();
		list.add(postId);
		//找到对应帖子
		List<ForumPost> moveList = forumPostDao.getMoveByIds(list);
		//找到新的版块,是否需要审核
		ForumBoard board = forumBoardService.findOne(newBoardId);
		boolean isCheck = board.getIsCheck() == 0?false:true;
		for(ForumPost c : moveList){
			if(c.getBoardId().equals(newBoardId)) {
				continue;
			}else {
				c.setBoardId(newBoardId);
				if(isCheck) {
					c.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
				}else {
					c.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
				}
				c = this.save(c);
				//找到主贴对应的回帖们 改变他们的版块
				List<ForumPost> postList = forumPostDao.getMoveSonByIds(c.getId());
				for (ForumPost forumPost : postList) {
					forumPost.setBoardId(newBoardId);
				}
				this.save(postList);
				/****************************** 论坛推送开始*******************************/
				if(StringUtils.equals(c.getCheckStatus(), ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue())) {
					Map<String,String> mapList = new HashMap<>();
						try {
							List<String> bs1 = forumBoardService.getUserBoards();
							String sendPath = ForumPostSendUtils.getSysImType(user.getCorpId(), user.getJwtToken());
							if(StringUtils.equals(c.getCreatedBy(), user.getUserId())) {
								mapList.put("isAuthor", "1" );
							}else {
								mapList.put("isAuthor", "0");
							}
							
							if (!CollectionUtils.isEmpty(bs1) && null != c) {
								if (bs1.indexOf(c.getBoardId()) >= 0) {
									mapList.put("isModerator", "1");
								}else {
									mapList.put("isModerator", "0");
								}
							}else {
								mapList.put("isModerator", "0");
							}
							String idss = "";	
							//所属人信息
							/*Map<String,Object> userMap =
									userApiService.getUser(user.getUserId(),user.getCorpId(),"",user.getJwtToken());
							mapList.put("userName", StringUtils.null2String(userMap.get("userName")));*/
							 if (c.getIsAnonymity() == 1) {
								 mapList.put("userName", "匿名");
								} else {
									if (StringUtils.equals(StringUtils.null2String(c.getAuthor()), "1")) {
										mapList.put("userName", "系统管理员");
									} else {
										Map<String, Object> us = userApiService.getUser(c.getAuthor(), user.getCorpId(), "", user.getJwtToken());
										if (us != null) {
											mapList.put("userName", us.get("userName").toString());
										}else {
											mapList.put("userName","用户不存在");
										}
									}
								}
						   String getScopeTypeValue = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope", "oa_forum_board", "id", StringUtils.null2String(board.getId()));
                           if (StringUtils.isNotBlank(getScopeTypeValue)) {
		            	         String[] idArr = getScopeTypeValue.split(",");
		            	         for (String id1 : idArr) {
		                	     idss += id1.split("SCOPE")[1] + ",";
		            	       }
		        	        }   
							mapList.put("sendPath", sendPath);
							mapList.put("id", c.getId());
							mapList.put("title", c.getTitle());
							mapList.put("checkStatus", c.getCheckStatus());
							mapList.put("author", c.getCreatedBy());
							mapList.put("boardId", c.getBoardId());
							mapList.put("rejection", c.getRejection());
							ForumPostSendUtils.sendMsg(mobileMessageService, request, user.getCorpId(), c.getAuthor(),"",mapList);
							Map<String,String> paramMaps = new HashMap<>();
							paramMaps.put("userId",user.getUserId());
							paramMaps.put("corpId",user.getCorpId());
							paramMaps.put("token",user.getJwtToken());
							paramMaps.put("msgTitle","新发表的帖子等待您的审核，请尽快完成");
							paramMaps.put("dataId", c.getId());
							paramMaps.put("msgContent","新发表的帖子等待您的审核，请尽快完成");
							paramMaps.put("url",ForumPostSendUtils.URL);
							paramMaps.put("PostId",c.getId());
							paramMaps.put("msgType","2");
							paramMaps.put("msgReceiver",idss);
							paramMaps.put("id",c.getId());
							paramMaps.put("checkStatus",c.getCheckStatus());
							ForumPostSendUtils.sendMsgToOffice(paramMaps);
						} catch (Exception e) {
							e.printStackTrace();
						}
				}
				/****************************** 论坛推送结束*******************************/
			}
		}
		return OperationResult.buildSuccessResult("移动成功");
	}
	
	
	/**
	 * 移动帖子
	 * @param ids
	 * @param id
	 * @return
	 */
	public OperationResult changePostStatus(String[] ids,String id,HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		List<ForumPost> moveList = forumPostDao.getMoveByIds(Arrays.asList(ids));
		ForumBoard board = forumBoardService.findOne(id);
		boolean isCheck = board.getIsCheck() == 0?false:true;
		for(ForumPost c : moveList){
			if(c.getBoardId().equals(id)) {
				continue;
			}else {
				c.setBoardId(id);
				//公告不需要审核
				if(isCheck && c.getPublistType() == 1) {
					c.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
				}else {
					c.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
				}
				c = this.save(c);
				
				List<ForumPost> postList = forumPostDao.getMoveSonByIds(c.getId());
				for (ForumPost forumPost : postList) {
					List<ForumPost> postListSon = forumPostDao.getMoveSonByIds(forumPost.getId());
					for(ForumPost forumSonPost : postListSon) {
						forumPost.setBoardId(id);
					}
					this.save(postListSon);
					forumPost.setBoardId(id);
				}
				this.save(postList);
				if(c.getCheckStatus().equals(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue())) {
					this.AllSearch(c,user,true,"0");
				}
				logService.saveModuleLog("forum:navigation:02", c.getTitle(), ""); 
				/****************************** 论坛推送开始*******************************/
				if(StringUtils.equals(c.getCheckStatus(), ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue()) ) {
					Map<String,String> mapList = new HashMap<>();
						try {
							List<String> bs1 = forumBoardService.getUserBoards();
							String sendPath = ForumPostSendUtils.getSysImType(user.getCorpId(), user.getJwtToken());
							if(StringUtils.equals(c.getCreatedBy(), user.getUserId())) {
								mapList.put("isAuthor", "1" );
							}else {
								mapList.put("isAuthor", "0");
							}
							
							if (!CollectionUtils.isEmpty(bs1) && null != c) {
								if (bs1.indexOf(c.getBoardId()) >= 0) {
									mapList.put("isModerator", "1");
								}else {
									mapList.put("isModerator", "0");
								}
							}else {
								mapList.put("isModerator", "0");
							}
							String idss = "";	
							//所属人信息
							Map<String,Object> userMap =
									userApiService.getUser(user.getUserId(),user.getCorpId(),"",user.getJwtToken());
							mapList.put("userName", StringUtils.null2String(userMap.get("userName")));
							 if (c.getIsAnonymity() == 1) {
								 mapList.put("userName", "匿名");
								} else {
									if (StringUtils.equals(StringUtils.null2String(c.getAuthor()), "1")) {
										mapList.put("userName", "系统管理员");
									} else {
										Map<String, Object> us = userApiService.getUser(c.getAuthor(), user.getCorpId(), "", user.getJwtToken());
										if (us != null) {
											mapList.put("userName", us.get("userName").toString());
										}else {
											mapList.put("userName","用户不存在");
										}
									}
								}
						   String getScopeTypeValue = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope", "oa_forum_board", "id", StringUtils.null2String(board.getId()));
                           if (StringUtils.isNotBlank(getScopeTypeValue)) {
		            	         String[] idArr = getScopeTypeValue.split(",");
		            	         for (String id1 : idArr) {
		                	     idss += id1.split("SCOPE")[1] + ",";
		            	       }
		        	        }   
							mapList.put("sendPath", sendPath);
							mapList.put("id", c.getId());
							mapList.put("title", c.getTitle());
							mapList.put("checkStatus", c.getCheckStatus());
							mapList.put("author", c.getCreatedBy());
							mapList.put("boardId", c.getBoardId());
							mapList.put("rejection", c.getRejection());
							ForumPostSendUtils.sendMsg(mobileMessageService, request, user.getCorpId(), idss,"",mapList);
							Map<String,String> paramMaps = new HashMap<>();
							paramMaps.put("userId",user.getUserId());
							paramMaps.put("corpId",user.getCorpId());
							paramMaps.put("token",user.getJwtToken());
							paramMaps.put("msgTitle","新发表的帖子等待您的审核，请尽快完成");
							paramMaps.put("dataId", c.getId());
							paramMaps.put("msgContent","新发表的帖子等待您的审核，请尽快完成");
							paramMaps.put("url",ForumPostSendUtils.URL);
							paramMaps.put("PostId",c.getId());
							paramMaps.put("msgType","2");
							paramMaps.put("msgReceiver",idss);
							paramMaps.put("id",c.getId());
							paramMaps.put("checkStatus",c.getCheckStatus());
							ForumPostSendUtils.sendMsgToOffice(paramMaps);
						} catch (Exception e) {
							e.printStackTrace();
						}
				}
				/****************************** 论坛推送结束*******************************/
			}
		}
		Map resources = new HashMap();
		//国际化资源
		resources.put("i18NCode", "oa.forum.movesuc");
		return OperationResult.buildSuccessResult("移动成功",resources);
	}

	/**
	 * 帖子标签变动
	 * @param postId
	 * @param ids
	 * @return
	 */
	public OperationResult changeLabel(String postId, String ids) {
		//首先删除该帖子的所有标签
		forumPostLabelDao.delByPost(postId);
		//添加已选定的标签数据进入关联表
		List<ForumPostLabel> addList = new ArrayList<ForumPostLabel>();
		ForumPostLabel pl = null;
		String[] labelId = null ;
		if(StringUtils.isNotBlank(ids)) {
			labelId = ids.split(",");
		}
		if(labelId != null) {
			for(String id : labelId){
				pl = new ForumPostLabel();
				pl.setPostId(postId);
				pl.setLabelId(id);
				addList.add(pl);
			}
		}
		
		if(addList != null && !addList.isEmpty()){
			forumPostLabelService.save(addList);
		}
		Map resources = new HashMap();
		//国际化资源
		resources.put("i18NCode", "oa.forum.marksuc");
		return OperationResult.buildSuccessResult("标记操作已处理完成 ",resources);
	}
	/**
	 *
	 * @Title: replyPost
	 * @Description:
	 *     回复帖子
	 * @param entity
	 * @param request 
	 * @return
	 * @return: OperationResult
	 *
	 * @date 2017年11月27日 下午5:14:04
	 *
	 */
	private static String htmlEncode(char c) {
	    switch(c) {
	       case '&':
	           return"&amp;";
	       case '<':
	           return"&lt;";
	       case '>':
	           return"&gt;";
	       case '"':
	           return"&quot;";
	       case ' ':
	           return"&nbsp;";
	       default:
	           return c +"";
	    }
	}
	public OperationResult replyPost(ForumPost entity, HttpServletRequest request,String level,String receiversId) {
		//如果level为4 需要添加receiver字段
		if(StringUtils.equals(level, "4")) {
			//根据receiversId查询接收人
			//ForumPost receiverPost = this.findOne(receiversId);
			//entity.setReceiver(receiverPost.getAuthor());
			entity.setReceiver(receiversId);
		}
		String str = entity.getContent();
		StringBuilder encodeStrBuilder = new StringBuilder();
	    for (int i = 0, len = str.length(); i < len; i++) {
	       encodeStrBuilder.append(htmlEncode(str.charAt(i)));
	    }
	    str = encodeStrBuilder.toString();
	    entity.setContent(str);
		if(StringUtils.isNotBlank(entity.getPostId())){
			ForumPost p = this.findOne(entity.getPostId());
			entity.setBoardId(p.getBoardId());
			entity.setCheckStatus(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
			if(entity.getType() == POST_TYPE_REPLY_COMMENTS) {
				entity.setTitle("评论：" + p.getTitle());
			}else{
				entity.setTitle(ForumPostService.POST_REPLY_TITLE + p.getTitle());
			}
			request.setAttribute("mainPostAuthor", p.getAuthor());//判断评论者是否本人
			entity.setPublistType(p.getPublistType());//评论贴保存主贴的发布类型
			return editSave(entity, false,request,"");

		}
		return OperationResult.buildFailureResult("后台异常");
	}

	public boolean isCollectionPost(String id, String userId) {
		StringBuffer s1 = new StringBuffer();
		s1.append(" select s.scopeValue from oa_forum_post p left join oa_forum_scope s on s.fieldDataValue = p.is_collection where s.scopeValue = '"+userId+"' and p.id='"+id+"'");
		List<String> bs = this.getEntityManager().createNativeQuery(s1.toString()).getResultList();
		if(bs!=null&&bs.size()>0) {
			return true;
		}else {
			return false;
		}
	}

	/**
     * 
     * @Title: list
     * @Description:
     * 		待审核列表    
     * @param pageable
     * @param filter
     * @param token
	 * @param type 
	 * @param user 
     * @return 
     * @return: Page<Map>
     *
     * @date 2017年11月25日 下午4:00:27
     *
     */
	public List<Map> getCheckListDing(String page, String pageSize, String token, String title, String type, WebUser user) {
		int pageSizeInt = Integer.parseInt(pageSize);
		int start = (Integer.parseInt(page)-1)*pageSizeInt;
		StringBuffer s0 = new StringBuffer();
		s0.append(" select a.id,a.attId, a.title, a.author,a.isAnonymity, a.type,a.postId,a.checkStatus,a.boardName,fn_date_format(a.createdDate,'MM-dd HH:mm') createdDate, a.authorName, a.isModerator,a.typeName from ( ");
		s0.append(" select t.id,t.attId,t.title,t.author,t.isAnonymity,t.type,t.postId,t.checkStatus,t.boardName,t.createdDate, x.userName as authorName, t.isModerator,t.typeName from ( ");
		s0.append(" select DISTINCT c.id,c.att_id attId, c.title, c.author,c.is_anonymity as isAnonymity, c.type, c.post_id as postId, c.check_status as checkStatus, b.name as boardName, c.createdDate,  ");
		s0.append(" (select CASE WHEN :userName = 'admin' THEN 1 WHEN ss.id IS NOT NULL THEN 1 ELSE 0 END isModerator from oa_forum_moderator_scope ss where b.id = ss.fieldDataValue AND ss.fieldDataTable = 'oa_forum_board' AND ss.scopeType = 'user' AND ss.scopeValue = :userId ) as isModerator,type.name as typeName");
		s0.append(" FROM oa_forum_moderator_scope s, oa_forum_post c, oa_forum_board b, oa_forum_type type");
		s0.append(" where s.fieldDataValue = b.id and b.id = c.board_id  ");
		s0.append(" and c.corp_id = :corpId and c.check_status in (:status) and c.is_delete = 0 ");
		//s0.append(" and b.status = 1  ");
		s0.append(" and b.forum_type = type.id and type.is_delete = 0  and c.type = 1 ");
		s0.append(" and c.createdBy = :userId");
		s0.append(" ) t ");
		s0.append(" left join  ");
		s0.append(" (select u.id, u.user_name as userName from sys_user u where u.corp_id = :corpId ");
		s0.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		s0.append(" on x.id = t.author ");
		s0.append(" ) a where 1 = 1 ");
		if(StringUtils.isNotEmpty(title)) {
			s0.append(" and a.title like "+SqlUtils.escapeLikeValue(title));
		}
		s0.append(" ORDER BY a.createdDate desc");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("corpId", user.getCorpId());
		paramMap.put("userId", user.getUserId());
		List<String> statusList = new ArrayList<>();
		if("1".equals(type)) {
			statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
			paramMap.put("status", statusList);
		}else if("0".equals(type)){
			statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_CG.getValue());
			/*statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHBTG.getValue());*/
			paramMap.put("status", statusList);
		}
		
		paramMap.put("userName", user.getUserName());
		List<Map> r = super.findByListNativeQuery(s0.toString(), null, paramMap, start, pageSizeInt);
		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(user.getCorpId());
		List<String> sensitiveList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : list) {
			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}
		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
//		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(user.getCorpId());
//		List<String> sensitiveList = new ArrayList<String>();
//		for (ForumSensitive forumSensitive : list) {
//			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
//		}
		Iterator it = r.iterator();
//		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		while (it.hasNext()) {
			Map a = (Map) it.next();
			//附件
			a.put("attIdJson", this.transformAttachmentPlanform2Dd(StringUtils.null2String(a.get("attId"))));
			//每一条帖子的发帖人图像进行查询=====userId应为每个发帖人的userID,并非当前登录人的
			String author=StringUtils.null2String(a.get("author"));
			int imageNum = 0;
			String attId = StringUtils.null2String(a.get("attId"));
			if(attId !=null&&StringUtils.isNotBlank(attId)) {
				imageNum =  attId.split("\\|").length;
			}
			a.put("imageNum", imageNum);
			if(sensitiveList!=null&&sensitiveList.size()>0) {
				a.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, a.get("title").toString(), 2, "*"));
			}else {
				a.put("title", a.get("title").toString());
			}
			//敏感词替换
//			if(sensitiveList!=null&&sensitiveList.size()>0) {
//				a.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, a.get("title").toString(), 2, "*"));
//			}
			
			String isAnonymity=StringUtils.null2String(a.get("isAnonymity"));//如果是匿名就不去查了 1 匿名  0  实名
			Map<String, String> map=new HashMap<>();
			if("0".equals(isAnonymity)) {
			map=this.getImage(author,  user.getCorpId(),  token);
			}else {
				map.put("fileName", "");
				map.put("image", "");
			}
			a.putAll(map);
		}
		return r;
	}

	/**
	 * 查询数量
	 * @param pageable
	 * @param filter
	 * @param token
	 * @param appType
	 * @return
	 */
	public String queryUncheckCount( String token,String appType) {
		WebUser user = WebUtils.getCurrentUser();
		StringBuffer s0 = new StringBuffer();
		/*s0.append(" select count(1) from ( ");
		s0.append(" select t.id,t.attId,t.title,t.author,t.isAnonymity,t.type,t.postId,t.checkStatus,t.boardName,t.createdDate, x.userName as authorName from ( ");
		s0.append(" select DISTINCT c.id,c.att_id attId, c.title, c.author,c.is_anonymity as isAnonymity, c.type, c.post_id as postId, c.check_status as checkStatus, b.name as boardName, c.createdDate ");
		s0.append(" FROM oa_forum_moderator_scope s, oa_forum_post c, oa_forum_board b, oa_forum_type type");
		s0.append(" where s.fieldDataValue = b.id and b.id = c.board_id  ");
		s0.append(" and c.corp_id = :corpId and c.check_status = :status and c.is_delete = 0 ");
		s0.append(" and b.status = 1 and b.is_delete = 0 and b.forum_type = type.id and type.is_delete = 0 and type.status = 1 ");
		s0.append(" and c.createdBy = :userId");
		s0.append(" ) t ");
		s0.append(" left join  ");
		s0.append(" (select u.id, u.user_name as userName from sys_user u where u.is_delete = 0 and u.corp_id = :corpId ");
		s0.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		s0.append(" on x.id = t.author ");
		s0.append(" ) a where 1 = 1 ");*/
		s0.append(" select count(1) as count from ( ");
		s0.append(" select t.id,t.attId,t.title,t.author,t.isAnonymity,t.type,t.postId,t.checkStatus,t.boardName,t.createdDate, x.userName as authorName, t.isModerator,t.typeName from ( ");
		s0.append(" select DISTINCT c.id,c.att_id attId, c.title, c.author,c.is_anonymity as isAnonymity, c.type, c.post_id as postId, c.check_status as checkStatus, b.name as boardName, c.createdDate,  ");
		s0.append(" (select CASE WHEN :userName = 'admin' THEN 1 WHEN ss.id IS NOT NULL THEN 1 ELSE 0 END isModerator from oa_forum_moderator_scope ss where b.id = ss.fieldDataValue AND ss.fieldDataTable = 'oa_forum_board' AND ss.scopeType = 'user' AND ss.scopeValue = :userId ) as isModerator,type.name as typeName");
		s0.append(" FROM oa_forum_moderator_scope s, oa_forum_post c, oa_forum_board b, oa_forum_type type");
		s0.append(" where s.fieldDataValue = b.id and b.id = c.board_id  ");
		s0.append(" and c.corp_id = :corpId and c.check_status in (:status) and c.is_delete = 0 ");
		s0.append(" and b.status = 1 and b.is_delete = 0 and b.forum_type = type.id and type.is_delete = 0 and type.status = 1 and c.type = 1 ");
		s0.append(" and c.createdBy = :userId");
		s0.append(" ) t ");
		s0.append(" left join  ");
		s0.append(" (select u.id, u.user_name as userName from sys_user u where u.corp_id = :corpId ");
		s0.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		s0.append(" on x.id = t.author ");
		s0.append(" ) a where 1 = 1 ");
		s0.append(" ORDER BY a.createdDate desc");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("corpId", user.getCorpId());
		paramMap.put("userId", user.getUserId());
		paramMap.put("status", ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
		paramMap.put("userName", user.getUserName());
		/*Query query = this.getEntityManager().createNativeQuery(s0.toString()).setParameter("corpId", user.getCorpId())
				.setParameter("userId", user.getUserId()).setParameter("status", ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());*/
		List<Map> checkList = super.findByListNativeQuery(s0.toString(), null, paramMap);
		String count = "0";
		for (Map map : checkList) {
			count = map.get("count").toString();
		}
		/*String count = query.getSingleResult().toString();*/
		return count;
	}
	/**
     * 
     * @Title: list
     * @Description:
     * 		待审核列表    
     * @param pageable
     * @param filter
     * @param token
	 * @param user 
	 * @param type 
     * @return 
     * @return: Page<Map>
     *
     * @date 2017年11月25日 下午4:00:27
     *
     */
	public List<Map> getFavoriteListDing(String page, String pageSize, String token, String title, WebUser user) {
		int pageSizeInt = Integer.parseInt(pageSize);
		int start = (Integer.parseInt(page)-1)*pageSizeInt;
		StringBuffer s0 = new StringBuffer();
		s0.append(" select a.id,a.attId, a.title, a.author,a.publishTime,a.isAnonymity,a.isPetname,a.petname, a.type,a.postId,a.checkStatus,a.boardName,fn_date_format(a.createdDate,'MM-dd HH:mm') createdDate, a.authorName, a.isModerator,a.typeName,a.isCollection,a.replyCount,a.viewCount from ( ");
		s0.append(" select t.id,t.attId,t.title,t.author,t.publishTime,t.isAnonymity,t.isPetname,t.petname,t.type,t.postId,t.checkStatus,t.boardName,t.createdDate, x.userName as authorName, t.isModerator,t.typeName,t.isCollection,t.replyCount,t.viewCount from ( ");
		s0.append(" select DISTINCT c.id,c.att_id attId, c.title,c.publish_time as publishTime, c.author,c.is_anonymity as isAnonymity,c.is_petname as isPetname,c.petname, c.type, c.post_id as postId, c.check_status as checkStatus, b.name as boardName, c.createdDate, ");
		s0.append(" (select CASE WHEN :userName = 'admin' THEN 1 WHEN ss.id IS NOT NULL THEN 1 ELSE 0 END isModerator from oa_forum_moderator_scope ss where b.id = ss.fieldDataValue AND ss.fieldDataTable = 'oa_forum_board' AND ss.scopeType = 'user' AND ss.scopeValue = :userId ) as isModerator,os.reply_count as replyCount,os.view_count as viewCount,type.name as typeName");
		s0.append(" ,CASE WHEN ofs.id IS NULL THEN 0 ELSE 1 END AS isCollection ");
		s0.append(" FROM oa_forum_moderator_scope s, oa_forum_post c, oa_forum_board b, oa_forum_type type,oa_forum_scope ofs,oa_forum_post_statistics os  ");
		s0.append(" where s.fieldDataValue = b.id and b.id = c.board_id and ");
		s0.append("  c.corp_id = :corpId and c.check_status in (:status) and c.is_delete = 0 ");
		//s0.append(" and b.status = 1 ");
		s0.append("  and b.is_delete = 0 and b.forum_type = type.id and type.is_delete = 0  and c.type = 1 and ofs.fieldDataValue = c.is_collection and ofs.scopeValue = :userId and os.post_id = c.id  ");
		s0.append(" ) t ");
		s0.append(" left join  ");
		s0.append(" (select u.id, u.user_name as userName from sys_user u where u.corp_id = :corpId ");
		s0.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		s0.append(" on x.id = t.author ");
		s0.append(" ) a where 1 = 1 ");
		if(StringUtils.isNotEmpty(title)) {
			s0.append(" and a.title like "+ SqlUtils.escapeLikeValue(title));
		}
		s0.append(" ORDER BY a.publishTime desc");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		List<String> statusList = new ArrayList<>();
		statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		statusList.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		paramMap.put("status", statusList);
		paramMap.put("corpId", user.getCorpId());
		paramMap.put("userId", user.getUserId());
		paramMap.put("userName", user.getUserName());
		List<Map> r = super.findByListNativeQuery(s0.toString(), null, paramMap, start, pageSizeInt);
		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(user.getCorpId());
		List<String> sensitiveList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : list) {
			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}
		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
//		List<ForumSensitive> list =  forumSensitiveDao.getForumSensitive(user.getCorpId());
//		List<String> sensitiveList = new ArrayList<String>();
//		for (ForumSensitive forumSensitive : list) {
//			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
//		}
//		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		Iterator it = r.iterator();
		while (it.hasNext()) {
			Map a = (Map) it.next();
			//附件
			a.put("attIdJson", this.transformAttachmentPlanform2Dd(StringUtils.null2String(a.get("attId"))));
			//每一条帖子的发帖人图像进行查询=====userId应为每个发帖人的userID,并非当前登录人的
			String author=StringUtils.null2String(a.get("author"));
			int imageNum = 0;
			String attId = StringUtils.null2String(a.get("attId"));
			if(attId !=null&&StringUtils.isNotBlank(attId)) {
				imageNum =  attId.split("\\|").length;
			}
			a.put("imageNum", imageNum);
			String isAnonymity=StringUtils.null2String(a.get("isAnonymity"));//如果是匿名就不去查了 1 匿名  0  实名
			
			if (StringUtils.equals(isAnonymity, "1")) {
				if (StringUtils.equals(user.getUserId(), StringUtils.null2String(author))) {
					// 版主、管理员、自己查看的时候显示真实姓名+匿名标注
					if (StringUtils.equals(StringUtils.null2String(author), "1")) {
						a.put("authorName", "系统管理员(匿名)");
					} else {
						Map<String, Object> us = userApiService.getUser(author, user.getCorpId(), "", token);
						if (us != null) {
							a.put("authorName", us.get("userName") + "(匿名)");
						}
					}
				} else {
					a.put("authorName", "匿名");
				}
			} else {
				String isPetname=StringUtils.null2String(a.get("isPetname"));//如果是昵称 1 昵称  0  实名
				if (StringUtils.equals(isPetname, "1")) {
					String petname = a.get("petname").toString();
					/*if(!"".equals(petname) && petname.length()>3) {
						petname = petname.substring(0, 3);
					}*/
					if (StringUtils.equals(user.getUserId(), StringUtils.null2String(author))) {
						// 版主、管理员、自己查看的时候显示真实姓名+昵称
						if (StringUtils.equals(StringUtils.null2String(author), "1")) {
							a.put("authorName", "系统管理员("+petname+")");
						} else {
							Map<String, Object> us = userApiService.getUser(author, user.getCorpId(), "", token);
							if (us != null) {
								a.put("authorName", us.get("userName") + "("+petname+")");
							}
						}
					} else {
						a.put("authorName", petname);
					}
				}else {
					if (StringUtils.equals(StringUtils.null2String(author), "1")) {
						a.put("authorName", "系统管理员");
					} else {
						Map<String, Object> us = userApiService.getUser(author, user.getCorpId(), "", token);
						if (us != null) {
							a.put("authorName", us.get("userName"));
						}
					}
				}
			}
			
			/*if("1".equals(isAnonymity)&&!author.equals(user.getUserId())) {
				a.put("authorName", "匿名");
			}*/
			if(sensitiveList!=null&&sensitiveList.size()>0) {
				a.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, a.get("title").toString(), 2, "*"));
			}else {
				a.put("title", a.get("title").toString());
			}
			//敏感词替换
//			if(sensitiveList!=null&&sensitiveList.size()>0) {
//				a.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, a.get("title").toString(), 2, "*"));
//			}
			
			Map<String, String> map=new HashMap<>();
			if("0".equals(isAnonymity)) {
			map=this.getImage(author,  user.getCorpId(),  token);
			}else {
				map.put("fileName", "");
				map.put("image", "");
			}
			a.putAll(map);
		}
		return r;
	}

	/**
	 * 论坛首页通过类型获取帖子列表
	 * @param token
	 * @param selectType 分类选择1.最新发帖,2.最新回帖,3.热门帖子,4.精华帖子
	 * @param corpId
	 * @param showNumber
	 * @param userId 
	 * @param userName 
	 * @return
	 */
	public List<Map> getTypePostList(String token, String selectType, String corpId, String showNumber, 
			String userId, String userName,String orgId) {
		StringBuffer sql = new StringBuffer();
		List<String> ids =new ArrayList<>();
		ids.add(userId);
		if(StringUtils.isNotBlank(orgId)) {
			ids.add(orgId);
		}
		Map<String, Object> paramMap=new HashMap<>();
		sql.append(" select ");
		if("2".equals(selectType)) {
			sql.append("p.post_id as id,");
		}else {
			sql.append("p.id as id,");
		}
		sql.append(" case when (os.scopeValue = :userId or :userName = 'admin' or p.author = :userId or p.is_anonymity = 0) ");
		sql.append(" then su.user_name ELSE '匿名' END AS username,p.author ,p.is_petname as isPetname,p.petname,");
		//sql.append(" su.user_name AS username,p.author,p.is_petname as isPetname,p.petname,");
		sql.append(" p.title as title,p.is_essence,p.createdDate as createddate,p.lastModifiedDate,b.aplication_scope,b.name boardName,p.is_anonymity as isAnonymity,p.publish_time as publishTime from oa_forum_post p ");
		sql.append(" left join sys_user su on su.id = p.author ");
		if("3".equals(selectType)) {
			sql.append(" left join oa_forum_post_statistics ofps on ofps.post_id = p.id ");
		}/*else if("4".equals(selectType)) {
			sql.append(" left join oa_forum_post_label opl on opl.post_id = p.id ");
			sql.append(" left join oa_forum_label ol on ol.id = opl.label_id ");
		}*/
		sql.append(" inner join oa_forum_board b on p.board_id = b.id and b.is_delete = 0 and b.status = 1 ");
		sql.append(" inner join oa_forum_type type on b.forum_type = type.id and type.is_delete = 0 and type.status = 1 ");
		sql.append(" LEFT JOIN (SELECT os.scopeValue,os.fieldDataValue FROM oa_forum_moderator_scope os  WHERE os.scopeValue = :userId) os ");
		sql.append(" ON p.board_id = os.fieldDataValue  ");
		sql.append(" where p.is_delete = '0' and p.check_status in (:status)");
		//范围适配
		sql.append(" and ( b.aplication_scope IN (SELECT fieldDataValue from oa_forum_board_user_scope WHERE scopeValue IN( :ids ) AND fieldData = 'aplication_scope') ");
		sql.append(" or b.aplication_scope IS NULL ");//适配已有数据
		sql.append(" or b.aplication_scope  NOT IN (SELECT DISTINCT(fieldDataValue) FROM oa_forum_board_user_scope) ) ");
		if("1".equals(selectType)) {
			sql.append(" and p.type = :type");
			sql.append(" order by p.publish_time desc ,p.id desc");
			paramMap.put("type", POST_TYPE_NEW);
		}else if("2".equals(selectType)){
			sql.append(" and p.type = :type");
			sql.append(" order by p.publish_time desc ,p.id desc");
			paramMap.put("type", POST_TYPE_REPLY);
		}else if("3".equals(selectType)) {
			sql.append(" and p.type = :type");
			sql.append(" order by ofps.view_count desc, p.publish_time desc ,p.id desc");
			paramMap.put("type", POST_TYPE_NEW);
		}else if("4".equals(selectType)){
			/*sql.append(" and p.type = :type and ol.name = '"+ForumPost.CheckStatusEnum.JH.getValue()+"'");
			sql.append(" order by  p.publish_time desc ,p.id desc");*/
			/*paramMap.put("type", POST_TYPE_NEW);*/
			sql.append(" and p.is_essence = 1 ");
			sql.append(" order by p.lastModifiedDate desc, p.publish_time desc ,p.id desc ");
		}
		List<String> list = new ArrayList<>();
		list.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		list.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		paramMap.put("status", list);
		paramMap.put("userId", userId);
		paramMap.put("userName", userName);
		paramMap.put("ids", ids);
		List<Map> res = new ArrayList<>();
		res = super.findByListNativeQuery(sql.toString(), null, paramMap, 0, Integer.parseInt(showNumber));
		List<ForumSensitive> forumlist =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sensitiveList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : forumlist) {
			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}
		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		//敏感词初始化
//		List<ForumSensitive> senlist =  forumSensitiveDao.getForumSensitive(corpId);
//		List<String> sensitiveList = new ArrayList<String>();
//		for (ForumSensitive forumSensitive : senlist) {
//			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
//		}
//		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		Iterator it = res.iterator();
		while (it.hasNext()) {
			Map m = (Map) it.next();
			if(sensitiveList!=null&&sensitiveList.size()>0) {
				m.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, m.get("title").toString(), 2, "*"));
			}else {
				m.put("title", m.get("title").toString());
			}
			//敏感词替换
//			if(sensitiveList!=null&&sensitiveList.size()>0) {
//				m.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, m.get("title").toString(), 2, "*"));
//			}
			
			String isAnonymity=StringUtils.null2String(m.get("isAnonymity"));//如果是匿名就不去查了 1 匿名  0  实名
			String author=StringUtils.null2String(m.get("author"));
			if("1".equals(isAnonymity)) {
				if (StringUtils.equals(userId, StringUtils.null2String(author))) {
					if (StringUtils.equals(StringUtils.null2String(m.get("author")), "1")) {
						m.put("username", "系统管理员(匿名)");
					}else {
						m.put("username", m.get("username")+"(匿名)");
					}
				}else {
					m.put("username", "匿名");
				}
			}else {
				String isPetname=StringUtils.null2String(m.get("isPetname"));//如果是昵称就不去查了 1 昵称  0  实名
				if("1".equals(isPetname)) {
					String petname = m.get("petname")+"";
					/*if(!"".equals(petname) && petname.length()>3) {
						petname = petname.substring(0, 3);
					}*/
					if (StringUtils.equals(userId, StringUtils.null2String(author))) {
						if (StringUtils.equals(StringUtils.null2String(m.get("author")), "1")) {
							m.put("username", "系统管理员("+petname+")");
						}else {
							m.put("username", m.get("username")+"("+petname+")");
						}
					}else {
						m.put("username", petname);
					}
				}
			}
		}
		return res;
	}

	public List<Map> getRecommendBoardList(String token, String corpId, String showNumber,String userId) {
		StringBuffer sql = new StringBuffer();
		Map<String, Object> paramMap=new HashMap<>();
		sql.append(" select b.id,b.name, b.recommend_time as recommendTime, b.aplication_scope, type.id as pid from oa_forum_board b ");
		sql.append(" inner join oa_forum_type type on b.forum_type = type.id and type.is_delete = 0 and type.status = 1 ");
		sql.append(" where b.is_navigation = '1' and b.is_delete='0' and b.corp_id = :corpId and b.status = 1 ");
		paramMap.put("corpId", corpId);
		String scopeSql = cmpApplyScopeService.getInScopeDataSql(userId, "oa_forum_board_user_scope", "oa_forum_board", "aplication_scope",paramMap);
		sql.append(" AND " + scopeSql);
		sql.append(" order by b.recommend_time desc ");
		List<Map> res = new ArrayList<>();
		res = super.findByListNativeQuery(sql.toString(), null, paramMap, 0, Integer.parseInt(showNumber));
		return res;
	}

	public List<Map> getLastTitleByBoardId(String id) {
		StringBuffer sql = new StringBuffer();
		Map<String, Object> paramMap=new HashMap<>();
		sql.append(" select p.board_id as boradId,p.title from oa_forum_post p ");
		sql.append(" where p.board_id = :id and p.is_delete = '0' and p.check_status in (:status) and type = :type order by p.publish_time desc");
		paramMap.put("id", id);
		List<String> list = new ArrayList<>();
		list.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		list.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		paramMap.put("status", list);
		paramMap.put("type", POST_TYPE_NEW);
		List<Map> res = new ArrayList<>();
		res = super.findByListNativeQuery(sql.toString(), null, paramMap, 0, 1);
		return res;
	}

	/**
	 * 移动端卡片上显示前三条最新数据
	 * @param token
	 * @param corpId
	 * @param showNumber
	 * @param userId
	 * @param token 
	 * @return
	 */
	public List<Map> getPostCardList(String corpId, String showNumber, String userId, String token) {
		StringBuffer sql = new StringBuffer();
		Map<String, Object> paramMap=new HashMap<>();
		sql.append(" select ");
		sql.append("p.id as id,p.check_status as checkStatus,p.is_anonymity isAnonymity, ");
		sql.append(" case when (os.scopeValue = :userId or :userId = '1' or p.author = :userId or p.is_anonymity = 0) ");
		sql.append(" then su.user_name ELSE '匿名' END AS username,p.author ,ops.view_count as viewCount,p.publish_time as publishTime, ops.reply_count as replyCount,p.is_top as isTop,");
		sql.append( "p.title as title,p.createdDate as createddate from oa_forum_post p ");
		sql.append(" left join sys_user su on su.id = p.author ");
		sql.append(" inner join oa_forum_board b on p.board_id = b.id and b.is_delete = 0 and b.status = 1 ");
		sql.append(" inner join oa_forum_type type on b.forum_type = type.id and type.is_delete = 0 and type.status = 1 ");
		sql.append("LEFT JOIN (SELECT os.scopeValue,os.fieldDataValue FROM oa_forum_moderator_scope os  WHERE os.scopeValue = :userId) os ");
		sql.append("  ON p.board_id = os.fieldDataValue  ");
		sql.append("  left join oa_forum_post_statistics ops on ops.post_id = p.id ");
		sql.append(" where p.is_delete = '0' and p.check_status in (:status)");
		sql.append(" and p.type = :type");
		sql.append(" order by p.publish_time desc ,p.id desc");
		paramMap.put("type", POST_TYPE_NEW);
		List<String> list = new ArrayList<>();
		list.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		list.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		paramMap.put("status", list);
		paramMap.put("userId", userId);
		List<Map> res = new ArrayList<>();
		res = super.findByListNativeQuery(sql.toString(), null, paramMap, 0, Integer.parseInt(showNumber));
		List<ForumSensitive> senlist =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sensitiveList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : senlist) {
			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}
		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		//敏感词初始化
//		List<ForumSensitive> senlist =  forumSensitiveDao.getForumSensitive(corpId);
//		List<String> sensitiveList = new ArrayList<String>();
//		for (ForumSensitive forumSensitive : senlist) {
//			sensitiveList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
//		}
//		Map initKeyWord = SensitiveUtils.initKeyWord(sensitiveList);
		List<String> l = new ArrayList<String>();
		Iterator it = res.iterator();
		while (it.hasNext()) {
			Map m = (Map) it.next();
			String author=StringUtils.null2String(m.get("author"));
			if(author.equals(userId)){
				m.put("isAuthor", 1);
			}else{
				m.put("isAuthor", 0);
			}
			boolean isModerator = forumBoardService.IsModeratorOfPost(m.get("id").toString());
			m.put("isModerator", isModerator);
			l.add(m.get("id").toString());
			if(sensitiveList!=null&&sensitiveList.size()>0) {
				m.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, m.get("title").toString(), 2, "*"));
			}else {
				m.put("title", m.get("title").toString());
			}
			//敏感词替换
//			if(sensitiveList!=null&&sensitiveList.size()>0) {
//				m.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, m.get("title").toString(), 2, "*"));
//			}
			
/*			if (StringUtils.equals(StringUtils.null2String(m.get("author")), "1")) {
				if(!StringUtils.equals(StringUtils.null2String(m.get("username")), "匿名"))
				m.put("username", "系统管理员");
			}*/
			if (StringUtils.equals(m.get("isAnonymity").toString(), "1")) {
				if (StringUtils.equals(userId, StringUtils.null2String(m.get("author")))) {
					// 版主、管理员、自己查看的时候显示真实姓名+匿名标注
					if (StringUtils.equals(StringUtils.null2String(m.get("author")), "1")) {
						m.put("authorName", "系统管理员(匿名)");
					} else {
						Map<String, Object> us = userApiService.getUser(m.get("author").toString(), corpId, "", token);
						if (us != null) {
							m.put("authorName", us.get("userName") + "(匿名)");
						}
					}
				} else {
					m.put("authorName", "匿名");
				}
			} else {
				if (StringUtils.equals(StringUtils.null2String(m.get("author")), "1")) {
					m.put("authorName", "系统管理员");
				} else {
					Map<String, Object> us = userApiService.getUser(m.get("author").toString(), corpId, "", token);
					if (us != null) {
						m.put("authorName", us.get("userName"));
					}
				}
			}
			
			
			
//			
		}
		// 获取到所有的标签
				List<Map> allLabel = forumLabelService.findAllLabel(corpId);
				List<Map> r1 = null;
				if (l.size() > 0) {
					String sql2 = "select pl.post_id as postId, l.id from oa_forum_post_label pl INNER join oa_forum_label l on l.id = pl.label_id where pl.post_id in (:l) and l.is_delete = 0 and l.status = 1 order by postId, sort_no, createdDate desc, name desc ";
					Map<String, Object> paramMap2 = new HashMap<String, Object>();
					paramMap2.put("l", l);
					r1 = super.findByListNativeQuery(sql2.toString(), null, paramMap2);
				}
				List<Map> lables = new ArrayList();
				for (Map p : res) {
					lables = new ArrayList();
					Map topMap = new HashMap();
					if(StringUtils.equals(p.get("isTop").toString(), "1")) {
						topMap.put("name", "置顶");
						topMap.put("color", "danger");
						lables.add(topMap);
					}
					// 匹配帖子标签start
					if (l.size() > 0) {
						String pid = StringUtils.null2String(p.get("id"));
						for (Map sl : allLabel) {
							Boolean f = false;
							if (!CollectionUtils.isEmpty(r1)) {
								for (Map map : r1) {
									if (StringUtils.equals(sl.get("id").toString(), StringUtils.null2String(map.get("id")))
											&& StringUtils.equals(pid, StringUtils.null2String(map.get("postId")))) {
										f = true;
									}
								}
							}
							Map swapm = new HashMap();
							swapm.put("name", sl.get("name"));
							swapm.put("color", sl.get("color"));
							if (f) {
								lables.add(swapm);
							}
							
						}
					}
					p.put("labels", lables);
				}
		return res;
	}

	public Page<Map> allCommentList(Pageable pageable, List<PropertyFilter> filter, String token, String corpId, String id, WebUser user) {
		boolean flag = false;
		if(user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
			flag = true;
		}
		//回帖评论数据
		StringBuffer s3 = new StringBuffer();
		List<Map> commentsList = new ArrayList<>();
		Map<String,Object> paramMap = new HashMap<String,Object>();
			List<ForumPost> postList = forumPostDao.getPostCount(id);
			if(!postList.isEmpty()&&postList.size()>0) {
				s3.append(" select a.id , fn_date_format(a.createdDate,'yyyy-MM-dd HH:mm:ss') as createdDate,a.post_id as postId,a.title, ");
				if(GlobalConstant.isOracle()) {
					s3.append(" a.author,a.is_anonymity as isAnonymity,a.is_petname as isPetname,a.petname,replace(replace(a.content,chr(10),'\\n'),chr(13),'\\r') as content,a.receiver,b.status AS boardStatus,t.status AS typeStatus ");
				}else {
					s3.append(" a.author,a.is_anonymity as isAnonymity,a.is_petname as isPetname,a.petname,a.content,a.receiver,b.status AS boardStatus,t.status AS typeStatus ");
				}
				s3.append(" from oa_forum_post a LEFT JOIN oa_forum_board b ON a.board_id = b.id  ");
				s3.append(" LEFT JOIN oa_forum_type t ON t.id = b.forum_type ");
				s3.append(" WHERE a.post_id = :id and a.is_delete = 0 and a.type = "+POST_TYPE_REPLY_COMMENTS );
				paramMap.put("id", id);
				String s = s3.toString();
				if(postList.size()>2) {
					s = PropertyFilter.getSqlByFilterAndPageable("", s, "createdDate", filter, pageable);
				}else {
					s = PropertyFilter.getSqlByFilterAndPageable("", s, "createdDate", filter, pageable);
				}
				Page<Map> page = super.findByPageNativeSQL(pageable, s, paramMap);
				commentsList = page.getContent();
				//主贴的状态	
				String checkStatus = "";
				String mainPostAuthor = "";
				boolean mainPostIsAuthor =false;
				//upPostType2:评论的楼层 upPostType1:评论所在主贴
				List<ForumPost> upPostCheckStatusListType2 = forumPostDao.getUpContent(id);
				if(CollectionUtils.isNotEmpty(upPostCheckStatusListType2)) {
					ForumPost upPostType2 = upPostCheckStatusListType2.get(0);
					List<ForumPost> upPostCheckStatusListType1 = forumPostDao.getUpContent(upPostType2.getPostId());
					if(CollectionUtils.isNotEmpty(upPostCheckStatusListType1)) {
						ForumPost upPostType1 = upPostCheckStatusListType1.get(0);
						mainPostAuthor = upPostType1.getAuthor();
					}
					 checkStatus = upPostType2.getCheckStatus().toString();
				}
				if(StringUtils.equals(user.getUserId(), mainPostAuthor)) {
					mainPostIsAuthor = true;
				}
				for (Map map2 : commentsList) {
					map2.put("mainPostCheckStatus", checkStatus);
					map2.put("mainPostIsAuthor", mainPostIsAuthor);
					if(StringUtils.equals(user.getUserId(), StringUtils.null2String(map2.get("author")))) {
						map2.put("isAuthor", true);
					}else {
						map2.put("isAuthor", false);
					}
					if (StringUtils.equals(map2.get("isAnonymity").toString(), "1")) {
						if (StringUtils.equals(user.getUserId(), StringUtils.null2String(map2.get("author"))) || flag) {
							// 版主、管理员、自己查看的时候显示真实姓名+匿名标注
							if (StringUtils.equals(StringUtils.null2String(map2.get("author")), "1")) {
								map2.put("authorName", "系统管理员(匿名)");
								map2.put("receiverName", "");
							} else {
								//Map<String, Object> us = userApiService.getUser(map2.get("author").toString(), corpId, "", token);
								Map us = findUserName(map2.get("author").toString());
								if (us != null) {
									map2.put("authorName", us.get("user_name") + "(匿名)");
									map2.put("receiverName", "");
								}
							}
						} else {
							map2.put("authorName", "匿名");
							map2.put("receiverName", "");
						}
					} else {
						if (StringUtils.equals(map2.get("isPetname").toString(), "1")) {
							if (StringUtils.equals(user.getUserId(), StringUtils.null2String(map2.get("author"))) || flag) {
								// 版主、管理员、自己查看的时候显示真实姓名+昵称
								if (StringUtils.equals(StringUtils.null2String(map2.get("author")), "1")) {
									map2.put("authorName", "系统管理员("+map2.get("petname")+")");
									map2.put("receiverName", "");
								} else {
									//Map<String, Object> us = userApiService.getUser(map2.get("author").toString(), corpId, "", token);
									Map us = findUserName(map2.get("author").toString());
									if (us != null) {
										map2.put("authorName", us.get("user_name") + "("+map2.get("petname")+")");
										map2.put("receiverName", "");
									}
								}
							} else {
								map2.put("authorName", map2.get("petname"));
								map2.put("receiverName", "");
							}
						}else {
							if (StringUtils.equals(StringUtils.null2String(map2.get("author")), "1")) {
								map2.put("authorName", "系统管理员");
								map2.put("receiverName", "");
							} else {
								//Map<String, Object> us = userApiService.getUser(map2.get("author").toString(), corpId, "", token);
								//receiver不为空代表这是回复评论,为空代表这是回复回帖
								Map us = findUserName(map2.get("author").toString());
								if(map2.get("receiver")!=null) {
									if(StringUtils.equals(map2.get("receiver").toString(), "1")) {
										map2.put("authorName", us.get("user_name"));
										map2.put("receiverName", "@系统管理员");
									}else {
										ForumPost post = this.findOne(map2.get("receiver").toString());
										if(post != null) {
											Map receivers = findUserName(post.getAuthor());
											if (us != null) {
												map2.put("authorName", us.get("user_name"));
											}else {
												map2.put("authorName", "");
											}
											if(receivers!= null) {
												String receiverName = StringUtils.null2String(receivers.get("user_name"));
												if (StringUtils.equals(StringUtils.null2String(post.getIsAnonymity()), "1")) {
													if(flag) {
														receiverName =receiverName+"(匿名)";
													}else {
														receiverName = "匿名";
													}
												}else if(StringUtils.equals(StringUtils.null2String(post.getIsPetname()), "1")) {
													if(flag) {
														receiverName =receiverName+"("+StringUtils.null2String(post.getPetname())+")";
													}else {
														receiverName = StringUtils.null2String(post.getPetname());
													}
												}
												map2.put("receiverName", "@"+receiverName);
											}else {
												map2.put("receiverName", "");
											}
										}else {
											map2.put("authorName", us.get("user_name"));
											map2.put("receiverName", "");
										}
										
									}
								}
								else {
									map2.put("authorName", us.get("user_name"));
									map2.put("receiverName", "");
								}
							}
						}
					}
				}
				return page;
			}
		return null;
	}

	public List<Map> getCommentsDing(String page, String pageSize, String token, WebUser user, String id) {
		boolean flag = false;
		if(user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
			flag = true;
		}
		int pageSizeInt = Integer.parseInt(pageSize);
		int start = (Integer.parseInt(page)-1)*pageSizeInt;
		Map<String,Object> paramMap = new HashMap<String,Object>();
		StringBuffer s = new StringBuffer();
		s.append(" select p.id , fn_date_format(p.createdDate,'yyyy-MM-dd HH:mm:ss') as createdDate,p.post_id as postId,p.title, ");
		s.append(" p.author,p.is_anonymity as isAnonymity,p.is_petname as isPetname,p.petname,p.content,p.receiver,p.board_id,ofs.post_id parentId ");
		s.append(" from oa_forum_post p ");
		s.append(" left join oa_forum_post ofs on ofs.id = p.post_id");
		s.append(" where p.post_id = :id and p.is_delete = 0 and p.type = "+POST_TYPE_REPLY_COMMENTS);
		paramMap.put("id", id);
		s.append(" ORDER BY createdDate desc");
		//主贴的状态	
		String checkStatus = "";
		String mainPostAuthor = "";
		boolean mainPostIsAuthor =false;
		//upPostType2:评论的楼层 upPostType1:评论所在主贴
		List<ForumPost> upPostCheckStatusListType2 = forumPostDao.getUpContent(id);
		if(CollectionUtils.isNotEmpty(upPostCheckStatusListType2)) {
			ForumPost upPostType2 = upPostCheckStatusListType2.get(0);
			List<ForumPost> upPostCheckStatusListType1 = forumPostDao.getUpContent(upPostType2.getPostId());
			if(CollectionUtils.isNotEmpty(upPostCheckStatusListType1)) {
				ForumPost upPostType1 = upPostCheckStatusListType1.get(0);
				mainPostAuthor = upPostType1.getAuthor();
			}
			 checkStatus = upPostType2.getCheckStatus().toString();
		}
		if(StringUtils.equals(user.getUserId(), mainPostAuthor)) {
			mainPostIsAuthor = true;
		}
		List<Map> r = super.findByListNativeQuery(s.toString(), null, paramMap, start, pageSizeInt);
		for (Map map2 : r) {
			map2.put("mainPostIsAuthor", mainPostIsAuthor);
			map2.put("nowAuthor", user.getUserId());
			Map<String, String> mapImage=getImage(StringUtils.null2String(map2.get("author")),  user.getCorpId(),  token);
			map2.put("image", mapImage.get("image").toString());
			if(StringUtils.equals(user.getUserId(), StringUtils.null2String(map2.get("author")))) {
				map2.put("isAuthor", true);
			}else {
				map2.put("isAuthor", false);
			}
			ForumPost f = this.findOne(map2.get("parentId").toString());
			boolean isModerator = forumBoardService.IsModeratorOfPost(f.getId());
			if(StringUtils.equals(f.getCreatedBy(), user.getUserId())||isModerator||user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())) {
				map2.put("isModerator", true);
				
			}else {
				map2.put("isModerator", false);
				
			}
			if(StringUtils.equals(f.getCreatedBy(), StringUtils.null2String(map2.get("author")))) {
				map2.put("isParentAuthor", true);
			}else {
				map2.put("isParentAuthor", false);
			}
			
			String createdDate = map2.get("createdDate").toString();
			map2.put("createdDate", createdDate.substring(5,createdDate.length()));
			if (StringUtils.equals(map2.get("isAnonymity").toString(), "1")) {
				if (StringUtils.equals(user.getUserId(), StringUtils.null2String(map2.get("author"))) || flag) {
					// 版主、管理员、自己查看的时候显示真实姓名+匿名标注
					if (StringUtils.equals(StringUtils.null2String(map2.get("author")), "1")) {
						map2.put("authorName", "系统管理员(匿名)");
						map2.put("receiverName", "");
					} else {
						//Map<String, Object> us = userApiService.getUser(map2.get("author").toString(), user.getCorpId(), "", token);
						Map uss = findUserName(map2.get("author").toString());
						if (uss != null) {
							map2.put("authorName", uss.get("user_name") + "(匿名)");
							map2.put("receiverName", "");
						}
					}
				} else {
					map2.put("authorName", "匿名");
					map2.put("receiverName", "");
				}
			} else {
				if (StringUtils.equals(map2.get("isPetname").toString(), "1")) {
					String petname = map2.get("petname")+"";
					if (StringUtils.equals(user.getUserId(), StringUtils.null2String(map2.get("author"))) || flag) {
						// 版主、管理员、自己查看的时候显示真实姓名+昵称标注
						if (StringUtils.equals(StringUtils.null2String(map2.get("author")), "1")) {
							map2.put("authorName", "系统管理员("+petname+")");
							map2.put("receiverName", "");
						} else {
							//Map<String, Object> us = userApiService.getUser(map2.get("author").toString(), user.getCorpId(), "", token);
							Map uss = findUserName(map2.get("author").toString());
							if (uss != null) {
								map2.put("authorName", uss.get("user_name") + "("+petname+")");
								map2.put("receiverName", "");
							}
						}
					} else {
						map2.put("authorName", petname);
						map2.put("receiverName", "");
					}
				}else {
					//Map<String, Object> us = userApiService.getUser(map2.get("author").toString(), user.getCorpId(), "", token);
					Map uss = findUserName(map2.get("author").toString());
					//receiver不为空代表这是回复评论,为空代表这是回复回帖
					if(map2.get("receiver")!=null) {
						ForumPost post = this.findOne(map2.get("receiver").toString());
						Map receivers = findUserName(post.getAuthor());
						//Map<String, Object> receivers = userApiService.getUser(map2.get("receiver").toString(), user.getCorpId(), "", token);
						if (uss != null && receivers!= null) {
							String receiverName = StringUtils.null2String(receivers.get("user_name"));
							if (StringUtils.equals(StringUtils.null2String(post.getIsAnonymity()), "1")) {
								if(flag) {
									receiverName =receiverName+"(匿名)";
								}else {
									receiverName = "匿名";
								}
							}else if(StringUtils.equals(StringUtils.null2String(post.getIsPetname()), "1")) {
								if(flag) {
									receiverName =receiverName+"("+StringUtils.null2String(post.getPetname())+")";
								}else {
									receiverName = StringUtils.null2String(post.getPetname());
								}
							}
							map2.put("authorName", uss.get("user_name"));
							map2.put("receiverName", "回复@"+receiverName);
						}
					}else {
						if (uss != null ) {
						map2.put("authorName", uss.get("user_name"));
						map2.put("receiverName", "");
						}
					}
				}
			}
		}
		return r;
	}

	public Map viewReplyPost(String id, String appType, WebUser user) {
		Map map = new HashMap<>();
		ForumPost p = forumPostDao.getOne(id);
		Object attIdJson;
		if (appType == "dingding") {
			attIdJson = transformAttachmentPlanform2Dd(StringUtils.null2String(p.getAttId()));
		} else {
			attIdJson = getAttachmentFile(p.getAttId(), user.getJwtToken());
		}
		map.put("attIdJson", attIdJson);
		map.put("contentPost", StringUtils.null2String(p.getContent()));
		// TODO Auto-generated method stub
		return map;
	}
	
	/**
	 * pc端查询收到的评论,或者回复数量
	 * @param userId
	 * @param remindPageType
	 * @return
	 */
	public List<Map> findIfRead(String userId ,String remindPageType) {
		StringBuffer sql = new StringBuffer();
		Map<String, Object> values = new HashMap<String, Object>();
		sql.append(" select a.id,a.isRead  FROM(" );
		if("2".equals(remindPageType) || "1".equals(remindPageType)) {
			sql.append(" SELECT op.id id, ");
			sql.append(" op.is_read as isRead,op.createdDate  ");
			sql.append(" FROM oa_forum_post op ");
			sql.append(" LEFT JOIN  oa_forum_post p ON p.id = op.post_id");
			sql.append(" WHERE op.is_read = '1' AND op.author <> :userId AND p.author = :userId AND op.type = "+POST_TYPE_REPLY+" AND op.is_delete = 0 AND p.is_delete = 0 AND  p.check_status in (:status) AND p.is_delete = 0 AND op.is_delete = 0 AND (op.data_id = '0' or op.data_id is null) ");//
		}
		if("1".equals(remindPageType)) {
			sql.append(" UNION ALL ");
		}
		if("3".equals(remindPageType) || "1".equals(remindPageType)) {
			sql.append(" SELECT op1.id id,op1.is_read as isRead,op1.createdDate  ");
			sql.append(" FROM oa_forum_post op1 ");
			sql.append(" LEFT JOIN  oa_forum_post  p1 ON p1.id = op1.post_id ");
			sql.append(" LEFT JOIN  oa_forum_post  p2 ON p2.id = p1.post_id ");
			sql.append(" WHERE op1.is_read = '1' AND op1.author <> :userId AND p1.author = :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND p2.check_status in (:status) AND p2.is_delete = 0 AND p1.is_delete = 0 AND op1.is_delete = 0 AND op1.receiver IS NULL AND (op1.data_id = '0' or op1.data_id is null) ");//
			sql.append(" UNION ALL ");
			sql.append(" SELECT op1.id id,op1.is_read as isRead,op1.createdDate  ");
			sql.append(" FROM oa_forum_post op1 ");
			sql.append(" LEFT JOIN  oa_forum_post  p1 ON p1.id = op1.post_id ");
			sql.append(" LEFT JOIN  oa_forum_post  p2 ON p2.id = p1.post_id ");
			sql.append(" LEFT JOIN (SELECT author,id FROM oa_forum_post) p3 ON op1.receiver = p3.id ");
			sql.append(" WHERE op1.is_read = '1' AND op1.author <> :userId AND p3.author = :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND p2.check_status in (:status) AND p2.is_delete = 0 AND p1.is_delete = 0 AND op1.is_delete = 0 AND op1.receiver IS NOT NULL AND (op1.data_id = '0' or op1.data_id is null) ");//
		}
		sql.append(" ) a order by a.createdDate desc");
		values.put("userId", userId);
		List<String> status = new ArrayList<>();
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		values.put("status", status);
		String s = sql.toString();
		List<Map> allPost = super.findByListNativeQuery(s, null, values);
		return allPost;
	}
	
	public List<Map> findIfReadWihtDingding(String userId ) {
		StringBuffer sql = new StringBuffer();
		Map<String, Object> values = new HashMap<String, Object>();
		sql.append(" select a.id,a.isRead  FROM(" );
		sql.append(" SELECT op.id id, ");
		sql.append(" op.is_read as isRead,op.createdDate  ");
		sql.append(" FROM oa_forum_post op ");
		sql.append(" LEFT JOIN  oa_forum_post p ON p.id = op.post_id");
		sql.append(" WHERE op.author <> :userId AND p.author = :userId AND op.type = "+POST_TYPE_REPLY+" AND  p.check_status in (:status) AND p.is_delete = 0 AND op.is_delete = 0 AND (op.data_id = '0' or op.data_id is null) ");//op.is_delete = 0 AND p.is_delete = 0 AND
		sql.append(" UNION ALL ");
		sql.append(" SELECT op1.id id,op1.is_read as isRead,op1.createdDate  ");
		sql.append(" FROM oa_forum_post op1 ");
		sql.append(" LEFT JOIN  oa_forum_post  p1 ON p1.id = op1.post_id ");
		sql.append(" LEFT JOIN  oa_forum_post  p2 ON p2.id = p1.post_id ");
		sql.append(" WHERE op1.author <> :userId AND p1.author = :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND p2.check_status in (:status) AND p2.is_delete = 0 AND p1.is_delete = 0 AND op1.is_delete = 0 AND op1.receiver IS NULL AND (op1.data_id = '0' or op1.data_id is null) ");//op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND
		sql.append(" UNION ALL ");
		sql.append(" SELECT op1.id id,op1.is_read as isRead,op1.createdDate  ");
		sql.append(" FROM oa_forum_post op1 ");
		sql.append(" LEFT JOIN  oa_forum_post  p1 ON p1.id = op1.post_id ");
		sql.append(" LEFT JOIN  oa_forum_post  p2 ON p2.id = p1.post_id ");
		sql.append(" WHERE op1.author <> :userId AND op1.receiver = :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND p2.check_status in (:status) AND p2.is_delete = 0 AND p1.is_delete = 0 AND op1.is_delete = 0 AND op1.receiver IS NOT NULL AND (op1.data_id = '0' or op1.data_id is null) ");//op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND
		sql.append(" ) a order by a.createdDate desc");
		values.put("userId", userId);
		List<String> status = new ArrayList<>();
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		values.put("status", status);
		String s = sql.toString();
		List<Map> allPost = super.findByListNativeQuery(s, null, values);
		return allPost;
	}
	
	/**
	 * pc端查询是否已读
	 * @param userId
	 * @param remindPageType
	 * @return
	 */
	public boolean ifReadAll(String userId,String remindPageType) {
		List<Map> allPost = findIfRead(userId,remindPageType);
		int i = 0;
		if(CollectionUtils.isNotEmpty(allPost)) {
			for(Map map:allPost) {
				if(map.get("isRead")!=null ) {
					if(StringUtils.equals(map.get("isRead").toString(), "1")) {
						i++;
					}
				}
			}
		}
		if(i>0) {
			return true;
		}else {
			return false;
		}
	}
	
	/**
	 * pc端查询是否已读
	 * @param userId
	 * @param remindPageType
	 * @return
	 */
	public boolean ifReadAllWithDingding(String userId) {
		List<Map> allPost = findIfReadWihtDingding(userId);
		int i = 0;
		if(CollectionUtils.isNotEmpty(allPost)) {
			for(Map map:allPost) {
				if(map.get("isRead")!=null ) {
					if(StringUtils.equals(map.get("isRead").toString(), "1")) {
						i++;
					}
				}
			}
		}
		if(i>0) {
			return true;
		}else {
			return false;
		}
	}
	
	
	
	/**
	 * 已读评论或者已读回复
	 * @param userId
	 * @param remindPageType
	 */
	public void readAll(String userId ,String remindPageType) {
		List<Map> allPost = findIfRead(userId,remindPageType);
		if(CollectionUtils.isNotEmpty(allPost)) {
			for(Map map:allPost) {
				int i = forumPostDao.markRead(map.get("id").toString());
			}
		}
	}
	
	/**
	 * 移动端获取论坛动态信息
	 * @param page
	 * @param pageSize
	 * @param user
	 * @param remindPageType
	 * @return
	 */
	public List<Map> getRemindList(String page, String pageSize, WebUser user, String remindPageType) {
		int pageSizeInt = Integer.parseInt(pageSize);
		int start = (Integer.parseInt(page)-1)*pageSizeInt;
		StringBuffer sql = new StringBuffer();
		Map<String, Object> values = new HashMap<String, Object>();
		//全部已读(只有@我的和评论我的才能已读,我回复不能已读)
		if(!"1".equals(remindPageType)) {
			readAll(user.getUserId(),remindPageType);
		}
		sql.append(" select a.id,a.receiver,a.content ,a.author,a.remindIsAnonymity,a.isPetname,a.petname,a.isRead,a.postIsAnomity,a.createdDate,a.title title,a.postId,a.checkStatus,a.is_delete,a.postAuthor,a.type,a.board_id,a.boardDelete,a.boardStatus,a.typeStatus from ( " );
		//回复我的
		if("1".equals(remindPageType)) {
			sql.append(" SELECT op.id id,op.receiver,op.content ,op.author author,");
			sql.append(" op.is_anonymity as remindIsAnonymity,op.is_petname as isPetname,op.petname,op.is_read as isRead,op.board_id,op.type type,op.createdDate,p.is_delete,p.title title,p.author postAuthor,p.postIsAnomity,p.id postId,p.check_status checkStatus, op.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op ");
			sql.append(" LEFT JOIN ( SELECT p.author,p.check_status,p.content,p.id,p.is_anonymity as postIsAnomity,p.title,p.is_delete FROM oa_forum_post p ) p ON p.id = op.post_id");
			sql.append(" LEFT JOIN ( SELECT b.id,b.status boardStatus,b.forum_type type,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t. STATUS typeStatus FROM oa_forum_type t ) t ON b.type = t.id  ");
			sql.append(" WHERE op.author = :userId AND p.author <> :userId AND op.type = "+POST_TYPE_REPLY+" AND op.is_delete = 0 AND p.is_delete = 0 AND p.check_status in (:status)  AND (op.data_id = '0' or op.data_id is null) ");//
			sql.append(" UNION ALL ");
			sql.append(" SELECT op1.id id,op1.receiver,op1.content , op1.author author, op1.is_anonymity as remindIsAnonymity,op1.is_petname as isPetname,op1.petname,op1.is_read as isRead,op1.board_id, op1.type type,op1.createdDate ,p2.is_delete,p1.title title, p2.author postAuthor,p2.postIsAnomity,p1.id postId,p2.check_status checkStatus,op1.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op1 ");
			sql.append(" LEFT JOIN ( SELECT p1.id,p1.post_id,p1.author, p1.is_delete,p1.content,p1.title FROM oa_forum_post p1 ) p1 ON p1.id = op1.post_id ");
			sql.append(" LEFT JOIN ( SELECT p2.id,  p2.is_delete,p2.is_anonymity as postIsAnomity,p2.title, p2.check_status,p2.author FROM oa_forum_post p2 ) p2 ON p2.id = p1.post_id ");
			sql.append(" LEFT JOIN ( SELECT b.id, b.status boardStatus,b.forum_type type,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op1.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t. STATUS typeStatus FROM oa_forum_type t ) t ON b.type = t.id  ");
			sql.append(" WHERE op1.author = :userId AND p1.author <> :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND p2.check_status in (:status)   AND op1.receiver IS NULL AND (op1.data_id = '0' or op1.data_id is null) ");//
			sql.append(" UNION ALL ");
			sql.append(" SELECT op1.id id,op1.receiver,op1.content, op1.author author, op1.is_anonymity as remindIsAnonymity,op1.is_petname as isPetname,op1.petname,op1.is_read as isRead,op1.board_id, op1.type type,op1.createdDate,p2.is_delete,p3.title title, p2.author postAuthor,p2.postIsAnomity,p1.id postId,p2.check_status checkStatus,op1.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op1 ");
			sql.append(" LEFT JOIN ( SELECT p1.id,p1.post_id,p1.author, p1.is_delete FROM oa_forum_post p1 ) p1 ON p1.id = op1.post_id ");
			sql.append(" LEFT JOIN ( SELECT p2.id,p2.is_delete,p2.is_anonymity as postIsAnomity,p2.title, p2.check_status,p2.author FROM oa_forum_post p2 ) p2 ON p2.id = p1.post_id ");
			sql.append(" LEFT JOIN ( SELECT b.id, b.status boardStatus,b.forum_type type,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op1.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t. STATUS typeStatus FROM oa_forum_type t ) t ON b.type = t.id  ");
			sql.append(" LEFT JOIN ( SELECT p3.id,p3.author receiverPostAuthor,p3.content,p3.title FROM oa_forum_post p3 ) p3 ON op1.receiver = p3.id  ");
			sql.append(" WHERE op1.author = :userId AND p3.receiverPostAuthor <> :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND p2.check_status in (:status)   AND op1.receiver IS NOT NULL AND (op1.data_id = '0' or op1.data_id is null) ");//
		}
		//评论我的,remindPageType==2
		if("2".equals(remindPageType)) {
			sql.append(" SELECT op.id id,op.receiver,op.content content ,op.author author,");
			sql.append(" op.is_anonymity as remindIsAnonymity,op.is_petname as isPetname,op.petname,op.is_read as isRead,op.board_id,op.type type,op.createdDate,p.title title,p.content postContent,p.is_delete,p.author postAuthor,p.postIsAnomity,p.id postId,p.check_status checkStatus, op.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op ");
			sql.append(" LEFT JOIN ( SELECT p.author,p.check_status, p.id,p.is_anonymity as postIsAnomity, p.title,p.is_delete,p.content FROM oa_forum_post p ) p ON p.id = op.post_id");
			sql.append(" LEFT JOIN ( SELECT b.id,b.status boardStatus,b.forum_type type,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t. STATUS typeStatus FROM oa_forum_type t ) t ON b.type = t.id  ");
			sql.append(" WHERE op.author <> :userId AND p.author = :userId AND op.type = "+POST_TYPE_REPLY+" AND op.is_delete = 0 AND p.is_delete = 0 AND  p.check_status in (:status)  AND (op.data_id = '0' or op.data_id is null) ");//
		}
		//@我的,remindPageType==3
		if("3".equals(remindPageType)) {
			sql.append(" SELECT op1.id id,op1.receiver, op1.content content, op1.author author, op1.is_anonymity as remindIsAnonymity,op1.is_petname as isPetname,op1.petname,op1.is_read as isRead,op1.board_id, op1.type type,op1.createdDate , p1.title ,p2.content postContent,p2.is_delete, p2.author postAuthor,p2.postIsAnomity,p1.id postId,p2.check_status checkStatus,op1.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op1 ");
			sql.append(" LEFT JOIN ( SELECT p1.id,p1.post_id,p1.author, p1.is_delete,p1.title title FROM oa_forum_post p1 ) p1 ON p1.id = op1.post_id ");
			sql.append(" LEFT JOIN ( SELECT p2.id,  p2.is_delete,p2.is_anonymity as postIsAnomity,p2.check_status, p2.content,p2.author FROM oa_forum_post p2 ) p2 ON p2.id = p1.post_id ");
			sql.append(" LEFT JOIN ( SELECT b.id, b.status boardStatus,b.forum_type type,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op1.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t. STATUS typeStatus FROM oa_forum_type t ) t ON b.type = t.id  ");
			sql.append(" WHERE op1.author <> :userId AND p1.author = :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND p2.check_status in (:status)   AND op1.receiver IS NULL AND (op1.data_id = '0' or op1.data_id is null) ");//
			sql.append(" UNION ALL ");
			sql.append(" SELECT op1.id id,op1.receiver,op1.content content, op1.author author, op1.is_anonymity as remindIsAnonymity,op1.is_petname as isPetname,op1.petname,op1.is_read as isRead,op1.board_id, op1.type type,op1.createdDate , p3.title,p2.content postContent,p2.is_delete, p2.author postAuthor,p2.postIsAnomity,p1.id postId,p2.check_status checkStatus,op1.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op1 ");
			sql.append(" LEFT JOIN ( SELECT p1.id,p1.post_id,p1.author, p1.is_delete FROM oa_forum_post p1 ) p1 ON p1.id = op1.post_id ");
			sql.append(" LEFT JOIN ( SELECT p2.id,  p2.is_delete,p2.is_anonymity as postIsAnomity,p2.title, p2.check_status, p2.content,p2.author FROM oa_forum_post p2 ) p2 ON p2.id = p1.post_id ");
			sql.append(" LEFT JOIN ( SELECT b.id, b.status boardStatus,b.forum_type type,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op1.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t. STATUS typeStatus FROM oa_forum_type t ) t ON b.type = t.id  ");
			sql.append(" LEFT JOIN ( SELECT p3.id,p3.author receiverPostAuthor,p3.title title FROM oa_forum_post p3 ) p3 ON op1.receiver = p3.id  ");
			sql.append(" WHERE op1.author <> :userId AND p3.receiverPostAuthor = :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND p2.check_status in (:status)   AND op1.receiver IS NOT NULL AND (op1.data_id = '0' or op1.data_id is null) ");//
		}
		sql.append(" ) a order by a.createdDate desc");
		values.put("userId", user.getUserId());
		List<String> status = new ArrayList<>();
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		if("1".equals(remindPageType)) {
			status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHBTG.getValue());
			status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
		}
		values.put("status", status);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, values, start, pageSizeInt);
		String token = user.getJwtToken();
		for (Map map : list) {
			//查看对应版块信息
			map.put("remindPageType", remindPageType);
			map.put("level", "评论我的帖子:");
			if("1".equals(remindPageType)) {
				map.put("level", "评论:");
			}
			//如果是2级帖子,不需要处理
			map.put("upPostAuthor", "");
			map.put("reply", "");
			//判断是否有管理员权限
			boolean flag = false;
			if(user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
				flag = true;
			}
			//判断是否处在当前版块黑名单
			boolean blackListFlag = false;
			String boardId = StringUtils.null2String(map.get("board_id"));
			String moderatorStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope", "oa_forum_board", "id", StringUtils.null2String(map.get("board_id")));
			if(moderatorStr.indexOf(user.getUserId()) == -1 && !flag) {
				String userStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_board_user_scope", "oa_forum_board", "id", StringUtils.null2String(map.get("board_id")));
				if(userStr.indexOf(user.getUserId()) == -1) {
					blackListFlag = true;
				}
			}
			map.put("blackListFlag", blackListFlag);
			//如果是3级帖子,需要将回帖内容处理成 "3级评论//@2级评论人名 :2级评论内容"
			if(StringUtils.equals(map.get("type").toString(),"3")) {
				map.put("level", "@我的评论:");
				if(StringUtils.isNotEmpty(StringUtils.null2String(map.get("receiver")))) {
					map.put("level", "@我的回复:");
				}
				//查到对应2级帖子内容
				List<ForumPost> forumPostList = forumPostDao.getUpContent(map.get("postId").toString());
				ForumPost post = forumPostList.get(0);
				String content = post.getContent();
				String author = post.getAuthor();
				String upPostAuthor = "";
				Map uss = findUserName(author);
				if (StringUtils.equals(StringUtils.null2String(author), "1")){
					upPostAuthor = "系统管理员";
				}else {
					if(uss == null) {
						upPostAuthor = " ";
					}else {
						upPostAuthor = StringUtils.null2String(uss.get("user_name").toString());
					}	   
				}
				if("1".equals(remindPageType)) {
					String name  = "";
					if (StringUtils.equals(StringUtils.null2String(post.getIsAnonymity()), "1")) {
						upPostAuthor = "匿名";
					}else if(StringUtils.equals(StringUtils.null2String(post.getIsPetname()), "1")) {
						upPostAuthor = StringUtils.null2String(post.getPetname());
					}
					map.put("level", "@"+upPostAuthor+"的评论:");
					if(StringUtils.isNotEmpty(StringUtils.null2String(map.get("receiver")))) {
						String receiverName = "";
						ForumPost receiverPost = this.findOne(map.get("receiver").toString());
						if(receiverPost != null) {
							Map usss = findUserName(receiverPost.getAuthor());
							if (StringUtils.equals(StringUtils.null2String(author), "1")){
								receiverName = "系统管理员";
							}else {
								if(usss == null) {
									receiverName = "";
								}else {
									receiverName = StringUtils.null2String(usss.get("user_name").toString());
								}	   
							}
							if (StringUtils.equals(StringUtils.null2String(receiverPost.getIsAnonymity()), "1")) {
								receiverName = "匿名";
							}else if(StringUtils.equals(StringUtils.null2String(receiverPost.getIsPetname()), "1")) {
								receiverName = StringUtils.null2String(receiverPost.getPetname());
							}
							map.put("level", "@"+receiverName+"的回复:");
						}else {
							map.put("level", "@"+receiverName+"的回复:");
						}
					}
				}
				map.put("content",map.get("content"));
				map.put("upPostAuthor", " // @"+upPostAuthor+":");
				map.put("reply", content);
			}
			String createdDate = map.get("createdDate").toString();
			String date = createdDate.substring(5,7)+"月"+createdDate.substring(8,10)+"日 "+createdDate.substring(11,16);
			map.put("createdDate", date);
			//处理回帖人头像
			if (StringUtils.equals(map.get("remindIsAnonymity").toString(), "1")) {
				if (StringUtils.equals(user.getUserId(), StringUtils.null2String(map.get("author")))) {
					// 版主、管理员、自己查看的时候显示真实姓名+匿名标注
					if (StringUtils.equals(StringUtils.null2String(map.get("author")), "1")) {
						map.put("authorName", "系统管理员(匿名)");
						map.put("userPhotoPath", GlobalConstant.getFlexServerPath(null) + "fui/images/admin.png");
					} else {
						Map uss = findUserName(map.get("author").toString());
						if (uss != null) {
							map.put("authorName", uss.get("user_name").toString() + "(匿名)");
							map.put("userPhotoPath", GlobalConstant.getFlexServerPath(null) + "/"
									+ getUserImage(uss.get("sex"), uss.get("img_id"), token));
						}else {
							map.put("authorName", "被删用户");
							map.put("userPhotoPath", GlobalConstant.getFlexServerPath(null) + "/web/dist/fui/images/unknow.png");
						}
					}
				} else {
					map.put("authorName", "匿名");
					map.put("userPhotoPath", GlobalConstant.getFlexServerPath(null) + "/web/dist/fui/images/unknow.png");
				}
			} else {
				if(StringUtils.equals(map.get("isPetname").toString(), "1")) {
					String petname = map.get("petname").toString();
					/*if(!"".equals(petname) && petname.length()>3) {
						petname = petname.substring(0, 3);
					}*/
					if (StringUtils.equals(user.getUserId(), StringUtils.null2String(map.get("author")))) {
						// 版主、管理员、自己查看的时候显示真实姓名+昵称标注
						if (StringUtils.equals(StringUtils.null2String(map.get("author")), "1")) {
							map.put("authorName", "系统管理员("+petname+")");
							map.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/admin.png");
						} else {
							Map uss = findUserName(map.get("author").toString());
							if (uss != null) {
								map.put("authorName", uss.get("user_name").toString() + "("+petname+")");
								map.put("userPhotoPath", (StringUtils.isBlank(StringUtils.null2String(uss.get("img_id")))? GlobalConstant.getFlexOfficePageUrl(null): GlobalConstant.getFlexServerPath(null)) + "/"
										+ getUserImage(uss.get("sex"), uss.get("img_id"), token));
							}else {
								map.put("authorName", "被删用户");
								map.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
							}
						}
					} else {
						map.put("authorName", petname);
						map.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
					}
				}else {
					if (StringUtils.equals(StringUtils.null2String(map.get("author")), "1")) {
						map.put("authorName", "系统管理员");
						map.put("userPhotoPath", GlobalConstant.getFlexServerPath(null) + "fui/images/admin.png");
					} else {
						if(StringUtils.isNotEmpty(map.get("author").toString())) {
							Map us = findUserName(map.get("author").toString())==null ? null : findUserName(map.get("author").toString());
							if (us != null) {
								map.put("authorName", us.get("user_name"));
								map.put("userPhotoPath", GlobalConstant.getFlexServerPath(null) + "/"
										+ getUserImage(us.get("sex"), us.get("img_id"), token));
							}
						}
						
					}
				}
			} 
		}
		return list;
	}

	/**
	 * pc获取论坛动态信息
	 * @param pageable
	 * @param filter
	 * @param currentPage
	 * @param user
	 * @param remindPageType
	 * @return
	 */
	public Map getRemindPostAll(Pageable pageable, List<PropertyFilter> filter, String currentPage, WebUser user,String remindPageType) {
		StringBuffer sql = new StringBuffer();
		//全部已读(只有@我的和评论我的才能已读,我回复不能已读)
		if(!"1".equals(remindPageType)) {
			readAll(user.getUserId(),remindPageType);
		}
		//获取回复我的和评论我的数量
		List<Map> allPost1 = findIfRead(user.getUserId(),"2");
		List<Map> allPost2 = findIfRead(user.getUserId(),"3");
		//评论我的
		String contactMine = allPost1.size() >99? "99+" : allPost1.size()+"";
		//回复我的
		String commentMine = allPost2.size() >99? "99+" : allPost2.size()+"";
		Map<String, Object> values = new HashMap<String, Object>();
		if(GlobalConstant.isOracle()) {
			sql.append(" select a.id,a.receiver,replace(replace(a.content,chr(10),'\\n'),chr(13),'\\r') as content,a.author,a.remindIsAnonymity,a.isPetname,a.petname,a.isRead,a.postIsAnomity,a.createdDate,a.title title,a.mainPostTitle,a.postId,a.checkStatus,a.is_delete,a.postAuthor,a.type1,a.board_id,a.boardDelete,a.boardStatus,a.typeStatus from ( " );
		}else{
			sql.append(" select a.id,a.receiver,a.content,a.author,a.remindIsAnonymity,a.isPetname,a.petname,a.isRead,a.postIsAnomity,a.createdDate,a.title title,a.mainPostTitle,a.postId,a.checkStatus,a.is_delete,a.postAuthor,a.type1,a.board_id,a.boardDelete,a.boardStatus,a.typeStatus from ( " );
		}
		//回复我的
		if("1".equals(remindPageType)) {
			sql.append(" SELECT op.id id,op.receiver,op.content,op.author author,");
			sql.append(" op.is_anonymity as remindIsAnonymity,op.is_petname as isPetname,op.petname,op.is_read as isRead,op.board_id,op.type type1,op.createdDate,p.is_delete,p.content title,p.title mainPostTitle,p.author postAuthor,p.postIsAnomity,p.id postId,p.check_status checkStatus,op.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op ");
			sql.append(" LEFT JOIN ( SELECT p.author,p.check_status,p.content,p.id,p.is_anonymity as postIsAnomity,p.title,p.is_delete FROM oa_forum_post p ) p ON p.id = op.post_id");
			sql.append(" LEFT JOIN ( SELECT b.id,b.status boardStatus,b.forum_type type2,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t.STATUS typeStatus FROM oa_forum_type t ) t ON b.type2 = t.id  ");
			sql.append(" WHERE op.author = :userId AND p.author <> :userId AND op.type = "+POST_TYPE_REPLY+" AND op.is_delete = 0 AND p.is_delete = 0 AND p.check_status in (:status)  AND (op.data_id = '0' or op.data_id is null) ");//
			sql.append(" UNION ALL ");
			sql.append(" SELECT op1.id id,op1.receiver,op1.content,op1.author author,op1.is_anonymity as remindIsAnonymity,op1.is_petname as isPetname,op1.petname,op1.is_read as isRead,op1.board_id,op1.type type1,op1.createdDate,p2.is_delete,p1.content title,'' AS mainPostTitle,p2.author postAuthor,p2.postIsAnomity,p1.id postId,p2.check_status checkStatus,op1.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op1 ");
			sql.append(" LEFT JOIN ( SELECT p1.id,p1.post_id,p1.author,p1.is_delete,p1.content FROM oa_forum_post p1 ) p1 ON p1.id = op1.post_id ");
			sql.append(" LEFT JOIN ( SELECT p2.id,p2.is_delete,p2.is_anonymity as postIsAnomity,p2.title,p2.check_status,p2.author FROM oa_forum_post p2 ) p2 ON p2.id = p1.post_id ");
			sql.append(" LEFT JOIN ( SELECT b.id,b.status boardStatus,b.forum_type type3,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op1.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t.STATUS typeStatus FROM oa_forum_type t ) t ON b.type3 = t.id  ");
			sql.append(" WHERE op1.author = :userId AND p1.author <> :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND p2.check_status in (:status)   AND op1.receiver IS NULL AND (op1.data_id = '0' or op1.data_id is null) ");//
			sql.append(" UNION ALL ");
			sql.append(" SELECT op1.id id,op1.receiver,op1.content,op1.author author,op1.is_anonymity as remindIsAnonymity,op1.is_petname as isPetname,op1.petname,op1.is_read as isRead,op1.board_id,op1.type type1,op1.createdDate,p2.is_delete,p3.content title,'' AS mainPostTitle,p2.author postAuthor,p2.postIsAnomity,p1.id postId,p2.check_status checkStatus,op1.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op1 ");
			sql.append(" LEFT JOIN ( SELECT p1.id,p1.post_id,p1.author,p1.is_delete FROM oa_forum_post p1 ) p1 ON p1.id = op1.post_id ");
			sql.append(" LEFT JOIN ( SELECT p2.id,p2.is_delete,p2.is_anonymity as postIsAnomity,p2.title,p2.check_status,p2.author FROM oa_forum_post p2 ) p2 ON p2.id = p1.post_id ");
			sql.append(" LEFT JOIN ( SELECT b.id,b.status boardStatus,b.forum_type type4,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op1.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t.STATUS typeStatus FROM oa_forum_type t ) t ON b.type4 = t.id  ");
			sql.append(" LEFT JOIN ( SELECT p3.id,p3.author receiverPostAuthor,p3.content FROM oa_forum_post p3 ) p3 ON op1.receiver = p3.id  ");
			sql.append(" WHERE op1.author = :userId AND p3.receiverPostAuthor <> :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND p2.check_status in (:status)   AND op1.receiver IS NOT NULL AND (op1.data_id = '0' or op1.data_id is null) ");//
		}
		//评论我的,remindPageType==2
		if("2".equals(remindPageType)) {
			sql.append(" SELECT op.id id,op.receiver,op.content,op.author author,");
			sql.append(" op.is_anonymity as remindIsAnonymity,op.is_petname as isPetname,op.petname,op.is_read as isRead,op.board_id,op.type type1,op.createdDate,p.title title,' ' AS mainPostTitle,p.content postContent,p.is_delete,p.author postAuthor,p.postIsAnomity,p.id postId,p.check_status checkStatus,op.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op ");
			sql.append(" LEFT JOIN ( SELECT p.author,p.check_status,p.id,p.is_anonymity as postIsAnomity,p.title,p.is_delete,p.content FROM oa_forum_post p ) p ON p.id = op.post_id");
			sql.append(" LEFT JOIN ( SELECT b.id,b.status boardStatus,b.forum_type type2,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t.STATUS typeStatus FROM oa_forum_type t ) t ON b.type2 = t.id  ");
			sql.append(" WHERE op.author <> :userId AND p.author = :userId AND op.type = "+POST_TYPE_REPLY+" AND op.is_delete = 0 AND p.is_delete = 0 AND  p.check_status in (:status)  AND (op.data_id = '0' or op.data_id is null) ");//
		}
		//@我的,remindPageType==3
		if("3".equals(remindPageType)) {
			sql.append(" SELECT op1.id id,op1.receiver,op1.content,op1.author author,op1.is_anonymity as remindIsAnonymity,op1.is_petname as isPetname,op1.petname,op1.is_read as isRead,op1.board_id,op1.type type1,op1.createdDate,p1.title,' ' AS mainPostTitle,p2.content postContent,p2.is_delete,p2.author postAuthor,p2.postIsAnomity,p1.id postId,p2.check_status checkStatus,op1.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op1 ");
			sql.append(" LEFT JOIN ( SELECT p1.id,p1.post_id,p1.author,p1.is_delete,p1.content title FROM oa_forum_post p1 ) p1 ON p1.id = op1.post_id ");
			sql.append(" LEFT JOIN ( SELECT p2.id,p2.is_delete,p2.is_anonymity as postIsAnomity,p2.check_status,p2.content,p2.author FROM oa_forum_post p2 ) p2 ON p2.id = p1.post_id ");
			sql.append(" LEFT JOIN ( SELECT b.id,b.status boardStatus,b.forum_type type2,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op1.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t.STATUS typeStatus FROM oa_forum_type t ) t ON b.type2 = t.id  ");
			sql.append(" WHERE op1.author <> :userId AND p1.author = :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND p2.check_status in (:status)   AND op1.receiver IS NULL AND (op1.data_id = '0' or op1.data_id is null) ");//
			sql.append(" UNION ALL ");
			sql.append(" SELECT op1.id id,op1.receiver,op1.content,op1.author author,op1.is_anonymity as remindIsAnonymity,op1.is_petname as isPetname,op1.petname,op1.is_read as isRead,op1.board_id,op1.type type1,op1.createdDate,p3.title,' ' AS mainPostTitle,p2.content postContent,p2.is_delete,p2.author postAuthor,p2.postIsAnomity,p1.id postId,p2.check_status checkStatus,op1.data_id dataId,b.boardDelete,b.boardStatus,t.typeStatus ");
			sql.append(" FROM oa_forum_post op1 ");
			sql.append(" LEFT JOIN ( SELECT p1.id,p1.post_id,p1.author,p1.is_delete FROM oa_forum_post p1 ) p1 ON p1.id = op1.post_id ");
			sql.append(" LEFT JOIN ( SELECT p2.id,p2.is_delete,p2.is_anonymity as postIsAnomity,p2.title,p2.check_status,p2.content,p2.author FROM oa_forum_post p2 ) p2 ON p2.id = p1.post_id ");
			sql.append(" LEFT JOIN ( SELECT b.id,b.status boardStatus,b.forum_type type3,b.is_delete boardDelete FROM oa_forum_board b ) b ON b.id = op1.board_id ");
			sql.append(" LEFT JOIN ( SELECT t.id,t.STATUS typeStatus FROM oa_forum_type t ) t ON b.type3 = t.id  ");
			sql.append(" LEFT JOIN ( SELECT p3.id,p3.author receiverPostAuthor,p3.content title FROM oa_forum_post p3 ) p3 ON op1.receiver = p3.id  ");
			sql.append(" WHERE op1.author <> :userId AND p3.receiverPostAuthor = :userId AND op1.type = "+POST_TYPE_REPLY_COMMENTS+" AND op1.is_delete = 0 AND p1.is_delete = 0 AND p2.is_delete = 0 AND p2.check_status in (:status)   AND op1.receiver IS NOT NULL AND (op1.data_id = '0' or op1.data_id is null) ");//
		}
		sql.append(" ) a order by a.createdDate desc");
		values.put("userId", user.getUserId());
		List<String> status = new ArrayList<>();
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		if("1".equals(remindPageType)) {
			status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHBTG.getValue());
			status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
		}
		values.put("status", status);
		String s = sql.toString();
		s = PropertyFilter.getSqlByFilterAndPageable("t", s, "", filter, pageable);
		Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
		List<Map> list = page.getContent();
		String token = user.getJwtToken();
		for (Map map : list) {
			//查看对应版块信息
			map.put("remindPageType", remindPageType);
			map.put("level", "评论我的帖子:");
			if("1".equals(remindPageType)) {
				map.put("level", "评论:");
				//处理Oracle产生的title与content类型不同产生的问题
				if(StringUtils.equals(StringUtils.null2String(map.get("type")), "2")) {
					map.put("title", StringUtils.null2String(map.get("mainPostTitle")));
				}
			}
			//如果是2级帖子,不需要处理
			map.put("upPostAuthor", "");
			map.put("reply", "");
			//判断是否有管理员权限
			boolean flag = false;
			if(user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
				flag = true;
			}
			//判断是否处在当前版块黑名单
			boolean blackListFlag = false;
			String boardId = StringUtils.null2String(map.get("board_id"));
			String moderatorStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_moderator_scope", "oa_forum_board", "id", StringUtils.null2String(map.get("board_id")));
			if(moderatorStr.indexOf(user.getUserId()) == -1 && !flag) {
				String userStr = popUserScopeUtilService.getScopeTypeValue("oa_forum_board_user_scope", "oa_forum_board", "id", StringUtils.null2String(map.get("board_id")));
				if(userStr.indexOf(user.getUserId()) == -1) {
					blackListFlag = true;
				}
			}
			map.put("blackListFlag", blackListFlag);
			//如果是3级帖子,需要将回帖内容处理成 "3级评论//@2级评论人名 :2级评论内容"
			if(StringUtils.equals(map.get("type1").toString(),"3")) {
				map.put("level", "@我的评论:");
				if(StringUtils.isNotEmpty(StringUtils.null2String(map.get("receiver")))) {
					map.put("level", "@我的回复:");
				}
				//查到对应2级帖子内容
				List<ForumPost> forumPostList = forumPostDao.getUpContent(map.get("postId").toString());
				ForumPost post = forumPostList.get(0);
				String content = post.getContent();
				String author = post.getAuthor();
				String upPostAuthor = "";
				Map uss = findUserName(author);
				if (StringUtils.equals(StringUtils.null2String(author), "1")){
					upPostAuthor = "系统管理员";
				}else {
					if(uss == null) {
						upPostAuthor = " ";
					}else {
						upPostAuthor = StringUtils.null2String(uss.get("user_name").toString());
					}	   
				}
				if("1".equals(remindPageType)) {
					String name  = "";
					if (StringUtils.equals(StringUtils.null2String(post.getIsAnonymity()), "1")) {
						upPostAuthor = "匿名";
					}else if(StringUtils.equals(StringUtils.null2String(post.getIsPetname()), "1")) {
						upPostAuthor = StringUtils.null2String(post.getPetname());
					}
					map.put("level", "@"+upPostAuthor+"的评论:");
					if(StringUtils.isNotEmpty(StringUtils.null2String(map.get("receiver")))) {
						String receiverName = "";
						ForumPost receiverPost = this.findOne(map.get("receiver").toString());
						if(receiverPost != null) {
							Map usss = findUserName(receiverPost.getAuthor());
							if (StringUtils.equals(StringUtils.null2String(author), "1")){
								receiverName = "系统管理员";
							}else {
								if(usss == null) {
									receiverName = "";
								}else {
									receiverName = StringUtils.null2String(usss.get("user_name").toString());
								}	   
							}
							if (StringUtils.equals(StringUtils.null2String(receiverPost.getIsAnonymity()), "1")) {
								receiverName = "匿名";
							}else if(StringUtils.equals(StringUtils.null2String(receiverPost.getIsPetname()), "1")) {
								receiverName = StringUtils.null2String(receiverPost.getPetname());
							}
							map.put("level", "@"+receiverName+"的回复:");
						}else {
							map.put("level", "@"+receiverName+"的回复:");
						}
					}
				}
				map.put("content",map.get("content"));
				map.put("upPostAuthor", " // @"+upPostAuthor+":");
				map.put("reply", content);
			}
			String createdDate = map.get("createdDate").toString();
			String date = createdDate.substring(5,7)+"月"+createdDate.substring(8,10)+"日 "+createdDate.substring(11,16);
			map.put("createdDate", date);
			//处理回帖人头像
			if (StringUtils.equals(map.get("remindIsAnonymity").toString(), "1")) {
				if (StringUtils.equals(user.getUserId(), StringUtils.null2String(map.get("author")))) {
					// 版主、管理员、自己查看的时候显示真实姓名+匿名标注
					if (StringUtils.equals(StringUtils.null2String(map.get("author")), "1")) {
						map.put("authorName", "系统管理员(匿名)");
						map.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/admin.png");
					} else {
						Map uss = findUserName(map.get("author").toString());
						if (uss != null) {
							map.put("authorName", uss.get("user_name").toString() + "(匿名)");
							map.put("userPhotoPath", (StringUtils.isBlank(StringUtils.null2String(uss.get("img_id")))? GlobalConstant.getFlexOfficePageUrl(null): GlobalConstant.getFlexServerPath(null)) + "/"
									+ getUserImage(uss.get("sex"), uss.get("img_id"), token));
						}else {
							map.put("authorName", "被删用户");
							map.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
						}
					}
				} else {
					map.put("authorName", "匿名");
					map.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
				}
			} else {
				if(StringUtils.equals(map.get("isPetname").toString(), "1")) {
					String petname = map.get("petname").toString();
					/*if(!"".equals(petname) && petname.length()>3) {
						petname = petname.substring(0, 3);
					}*/
					if (StringUtils.equals(user.getUserId(), StringUtils.null2String(map.get("author")))) {
						// 版主、管理员、自己查看的时候显示真实姓名+昵称标注
						if (StringUtils.equals(StringUtils.null2String(map.get("author")), "1")) {
							map.put("authorName", "系统管理员("+petname+")");
							map.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/admin.png");
						} else {
							Map uss = findUserName(map.get("author").toString());
							if (uss != null) {
								map.put("authorName", uss.get("user_name").toString() + "("+petname+")");
								map.put("userPhotoPath", (StringUtils.isBlank(StringUtils.null2String(uss.get("img_id")))? GlobalConstant.getFlexOfficePageUrl(null): GlobalConstant.getFlexServerPath(null)) + "/"
										+ getUserImage(uss.get("sex"), uss.get("img_id"), token));
							}else {
								map.put("authorName", "被删用户");
								map.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
							}
						}
					} else {
						map.put("authorName", petname);
						map.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/unknow.png");
					}
				}else{
					if (StringUtils.equals(StringUtils.null2String(map.get("author")), "1")) {
						map.put("authorName", "系统管理员");
						map.put("userPhotoPath", GlobalConstant.getFlexOfficePageUrl(null) + "/web/dist/fui/images/admin.png");
					} else {
						if(StringUtils.isNotEmpty(map.get("author").toString())) {
							Map us = findUserName(map.get("author").toString())==null ? null : findUserName(map.get("author").toString());
							if (us != null) {
								map.put("authorName", us.get("user_name"));
								map.put("userPhotoPath", (StringUtils.isBlank(StringUtils.null2String(us.get("img_id")))? GlobalConstant.getFlexOfficePageUrl(null): GlobalConstant.getFlexServerPath(null)) + "/"
										+ getUserImage(us.get("sex"), us.get("img_id"), token));
							}
						}
						
					}
				}
			} 
		}
		Map map = new HashMap<>();
		map.put("content", list);
		map.put("number", page.getNumber());
		map.put("contactMine", contactMine);
		map.put("commentMine", commentMine);
		map.put("numberOfElements", page.getNumberOfElements());
		map.put("size", page.getSize());
		map.put("sort", page.getSort());
		map.put("totalElements", page.getTotalElements());
		map.put("totalPages", page.getTotalPages());
		map.put("currentPage", currentPage);
		return map;
	}
	
	
	
	
	public Map initUserInfo(WebUser user) {
		Map map = new HashMap<>();
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		String token = user.getJwtToken();
		List<String> status = new ArrayList<>();
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		//计算当前用户发帖数量
		List<ForumPost>  postCountList = forumPostDao.getPostCountByAuthorAndType(user.getUserId(),user.getCorpId(),1,status);
		if(postCountList == null || postCountList.size() == 0) {
			map.put("postCount", 0);
		}else {
			map.put("postCount", postCountList.size());
		}
		//计算当前用户回帖数量
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT a.id from oa_forum_post a LEFT JOIN oa_forum_board b ON a.board_id = b.id ");
		sb.append(" WHERE a.author = :author AND a.corp_id = :corpId AND a.type = 2 AND a.is_delete = 0 AND a.check_status in (:status) AND b.status = 1 AND b.is_delete = 0 ");
		//List<ForumPost>  replyPostCountList = forumPostDao.getPostCountByAuthorAndType(user.getUserId(),user.getCorpId(),2,status);
		Map<String, Object> values = new HashMap<String, Object>();
		values.put("author", user.getUserId());
		values.put("status", status);
		values.put("corpId", corpId);
		List<Map> replyPostCountList =  super.findByListNativeQuery(sb.toString(), null, values);
		if(replyPostCountList == null || replyPostCountList.size() == 0) {
			map.put("replyPostCount", 0);
		}else {
			map.put("replyPostCount", replyPostCountList.size());
		}
		Integer collectionCount = this.getCollectionList(user);
		map.put("collectionCount", collectionCount);
		if (StringUtils.equals(user.getUserId(), "1")) {
			map.put("authorName", "系统管理员");
			map.put("userPhotoPath", GlobalConstant.getFlexServerPath(null) + "fui/images/admin.png");
		} else {
			Map<String, Object> us = userApiService.getUser(user.getUserId(), user.getCorpId(), "", user.getJwtToken());
			if (us != null) {
				map.put("authorName", us.get("userName"));
				map.put("userPhotoPath", GlobalConstant.getFlexServerPath(null) + "/"
						+ getUserImage(us.get("sex"), us.get("imgId"), user.getJwtToken()));
			}
		}
		Map<String, String> mapImage=getImage(userId,  corpId,  token);
		map.put("image", mapImage.get("image").toString());
		//map.put("ifReadAll", ifReadAllWithDingding(user.getUserId()));
		return map;
	}

	//获取个人收藏的帖子数量
	public Integer getCollectionList(WebUser user) {
		StringBuffer sb = new StringBuffer();
		sb.append(" select ofs.id from oa_forum_scope ofs ");
		sb.append(" left join oa_forum_post p on p.is_collection = ofs.fieldDataValue ");
		sb.append(" left join oa_forum_board b on b.id = p.board_id  ");
		sb.append(" where ofs.scopeValue = :userId and p.check_status in (:status) and p.is_delete = 0 and p.corp_id = :corpId  AND b.is_delete = 0 ");
		Map<String, Object> values = new HashMap<String, Object>();
		List<String> status = new ArrayList<>();
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_SHTG.getValue());
		status.add(ForumPost.CheckStatusEnum.CHECK_STATUS_WXSH.getValue());
		values.put("status", status);
		values.put("userId", user.getUserId());
		values.put("corpId", user.getCorpId());
		List<Map> list =  super.findByListNativeQuery(sb.toString(), null, values);
		if(list != null && list.size()>0) {
			return list.size();
		}
		return 0;
		
	}

	

	public OperationResult postPushMsg(ForumPost forum, WebUser user) {
		Map<String,String> map = new HashMap<>();
		map.put("msgType", "2");
		map.put("moduleCode", pushCode);
		map.put("corpId", user.getCorpId());
		map.put("dataId", forum.getId());
		/*map.put("receiver", ids+"]");*/
		String msg = restClient.post("/system/umc/message/takeMsgDone", user.getJwtToken(), map);
		// TODO Auto-generated method stub
		return null;
	}

	public OperationResult deleteRemind(String id) {
		String s1 = " UPDATE oa_forum_post set is_delete = '1' where id = :id ";
		int n = this.getEntityManager().createNativeQuery(s1).setParameter("id", id)
				.executeUpdate();
		if(n>0) {
			Map resources = new HashMap();
			//国际化资源
			resources.put("i18NCode", "oa.forum.deletetips4");
			return OperationResult.buildSuccessResult("删除成功");
		}else {
			return OperationResult.buildSuccessResult("删除失败");
		}
	}
	
	/**
	 * 获取对应主题帖的 总记录数 获取 当前传入评论/回帖 所在楼层
	 * @param id
	 * @return
	 */
	public Map<String , String> pageCount(String id){
		Map<String,String> map = new HashMap();
		String ID = id;
		String postId = null ;
		//先判断是"回帖"还是"评论"
		String sql1 = (" SELECT * from oa_forum_post where id = :id  ");
		Map<String, Object> param1 = new HashMap<String, Object>();
		param1.put("id", ID);
		List<Map> list1 = new ArrayList();
		list1 = super.findByListNativeQuery(sql1, null, param1);
		if(CollectionUtils.isNotEmpty(list1)) {
			//如果是评论,需要找到对应回帖的postId
			if(list1.get(0).get("type").toString().equals("3")) {
				//这是评论 找到对应回帖postId
				postId = list1.get(0).get("post_id").toString();
				String sql2 = (" SELECT post_id,id from oa_forum_post where id = :id and is_delete = '0' ");
				Map<String, Object> param2 = new HashMap<String, Object>();
				param2.put("id", postId);
				List<Map> list2 = new ArrayList();
				list2 = super.findByListNativeQuery(sql2, null, param2);
				//更改postId
				postId = list2.get(0).get("post_id").toString();
				ID = list2.get(0).get("id").toString();
			}else {
				//这是回帖 找到对应的postId
				String sql3 = (" SELECT post_id from oa_forum_post WHERE id= :id and is_delete = '0' ");
				Map<String, Object> param3 = new HashMap<String, Object>();
				param3.put("id", ID);
				List<Map> list3 = new ArrayList();
				list3 = super.findByListNativeQuery(sql3, null, param3);
				postId = list3.get(0).get("post_id").toString();
			}
			//查询对应主题帖一共有多少回帖
			String sql4 = (" SELECT ofp.id ,ofp.createdDate from oa_forum_post ofp WHERE post_id = :id and is_delete = '0' ORDER BY createdDate  ");
			Map<String, Object> param4 = new HashMap<String, Object>();
			param4.put("id", postId);
			List<Map> list4 = new ArrayList();
			//获取所有通过创建时间排序的回帖
			list4 = super.findByListNativeQuery(sql4, null, param4);
			//获取楼层数目
			int pageCount=0;
			for(int i = 0; i < list4.size(); i++) {
				pageCount++;
				if(list4.get(i).get("id").equals(ID)) {
					break;
				}
			}
			//再获取页码数
			String pageNumber ;
			if((pageCount%10) == 0) {
				pageNumber = (pageCount/10)+"";
			}else {
				pageNumber = ((pageCount/10)+1)+"";
			}
			map.put("pageNumber", pageNumber);
			map.put("floor", pageCount+"");
			map.put("floorId", ID);
		}
		return map;
	}
	
	/**
	 * 移动端获取待审核列表
	 * @param pageable
	 * @param filter
	 * @param token
	 * @param appType
	 * @param title
	 * @param corpId
	 * @return
	 */
	public List<Map> checkListDing(String page, String pageSize, List<PropertyFilter> filter, String token,String appType,String title, String corpId) {
		WebUser user = WebUtils.getCurrentUser();
		int pageSizeInt = Integer.parseInt(pageSize);
		int start = (Integer.parseInt(page)-1)*pageSizeInt;
		StringBuffer s0 = new StringBuffer();
		Map<String, Object> values = new HashMap<String, Object>();
		s0.append(" select a.id,a.attId, a.title, a.author,a.isAnonymity, a.type,a.postId,a.checkStatus,a.boardName,a.typeName,fn_date_format(a.createdDate,'MM-dd HH:mm') createdDate,fn_date_format(a.publishTime,'MM-dd HH:mm') publishTime,a.content, a.authorName from ( ");
		s0.append(" select t.id,t.attId,t.title,t.author,t.isAnonymity,t.type,t.postId,t.checkStatus,t.boardName,t.typeName,t.createdDate,t.publishTime,t.content, x.userName as authorName from ( ");
		s0.append(" select c.id,c.att_id attId, c.title, c.author,c.is_anonymity as isAnonymity, c.type, c.post_id as postId, c.check_status as checkStatus, b.name as boardName,type.name as typeName, c.createdDate,c.publish_time as publishTime, c.content ");
		s0.append(" FROM oa_forum_post c, oa_forum_board b, oa_forum_type type");
		if("admin".equals(user.getUserName())||user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())) {
			s0.append(" where ");
		}else {
			s0.append(" ,oa_forum_moderator_scope s where s.fieldDataValue = b.id and s.scopeValue = :userId and s.fieldDataTable = 'oa_forum_board' and s.scopeType = 'user' and ");
		}
		s0.append(" b.id = c.board_id and c.corp_id = :corpId and c.check_status = :status and c.is_delete = 0 and c.type = "+POST_TYPE_NEW+" ");
		s0.append(" and b.is_delete = 0 and b.forum_type = type.id and type.is_delete = 0 and type.status = 1 ");
		s0.append(" ) t ");
		s0.append(" left join  ");
		s0.append(" (select u.id, u.user_name as userName from sys_user u where u.corp_id = :corpId ");
		s0.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
		s0.append(" on x.id = t.author ");
		s0.append(" ) a where 1 = 1 ");
		if(StringUtils.isNotEmpty(title)) {
			s0.append(" and a.title like "+SqlUtils.escapeLikeValue(title));
		}
		s0.append(" ORDER BY a.createdDate desc ");
		if(!"admin".equals(user.getUserName())&&!user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())) {
			values.put("userId", user.getUserId());
		}
		values.put("corpId", user.getCorpId());
		values.put("status", ForumPost.CheckStatusEnum.CHECK_STATUS_WSH.getValue());
		
		String s = s0.toString();
		/*s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.createdDate desc ", filter, pageable);*/
		List<Map> r = super.findByListNativeQuery(s, null, values, start, pageSizeInt);
		List<ForumSensitive> sensitiveList =  forumSensitiveDao.getForumSensitive(corpId);
		List<String> sList = new ArrayList<String>();
		for (ForumSensitive forumSensitive : sensitiveList) {
			sList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
		}
		Map initKeyWord = SensitiveUtils.initKeyWord(sList);

/*		Page<Map> page = super.findByPageNativeSQL(pageable, s, values);*/
//		List<ForumSensitive> sensitiveList =  forumSensitiveDao.getForumSensitive(corpId);
//		List<String> sList = new ArrayList<String>();
//		for (ForumSensitive forumSensitive : sensitiveList) {
//			sList.addAll(Arrays.asList(forumSensitive.getSensitiveName().split(";"))) ;
//		}
//		Map initKeyWord = SensitiveUtils.initKeyWord(sList);
		/*Iterator it = map.getContent().iterator();*/
		Iterator it = r.iterator();
		while (it.hasNext()) {
			Map a = (Map) it.next();
			//处理时间
			String time = a.get("publishTime").toString();
			time = time.trim().replace("-", "月");
			time = time.trim().replace(" ", "日  ");
			if(time.startsWith("0")) {
				time = new StringBuffer(time).deleteCharAt(0).toString();
			}if(time.contains("月0")) {
				time = time.replaceAll("月0", "月");
			}
			a.put("publishTime", time);
			//获取用户角色权限
			boolean flag = false;
			if(user.getRoleCodes().contains(ForumPost.CheckStatusEnum.YYGLYQX.getValue())||SecurityUtils.isSuperAdmin(user)) {
				a.put("isAdminRole", true);
			}
			//附件
			Object attIdJson;
			if (appType == "dingding") {
				attIdJson = this.transformAttachmentPlanform2Dd(StringUtils.null2String(a.get("attId")));
			} else {
				attIdJson = this.getAttachmentFile(a.get("attId"), token);
			}
			a.put("attIdJson", attIdJson);
			if(sList!=null&&sList.size()>0) {
				a.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, a.get("title").toString(), 2, "*"));
			}else {
				a.put("title", a.get("title").toString());
			}
			//敏感词替换
//			if(sList!=null&&sList.size()>0) {
//				a.put("title", SensitiveUtils.replaceSensitiveWord(initKeyWord, a.get("title").toString(), 2, "*"));
//			}
			
			//每一条帖子的发帖人图像进行查询=====userId应为每个发帖人的userID,并非当前登录人的
			String author=StringUtils.null2String(a.get("author"));
			String isAnonymity=StringUtils.null2String(a.get("isAnonymity"));//如果是匿名就不去查了 1 匿名  0  实名
			if (StringUtils.equals(isAnonymity, "1")) {
				if (StringUtils.equals(user.getUserId(), StringUtils.null2String(author))) {
					// 版主、管理员、自己查看的时候显示真实姓名+匿名标注
					if (StringUtils.equals(StringUtils.null2String(author), "1")) {
						a.put("authorName", "系统管理员(匿名)");
					} else {
						Map<String, Object> us = userApiService.getUser(author, user.getCorpId(), "", token);
						if (us != null) {
							a.put("authorName", us.get("userName") + "(匿名)");
						}
					}
				} else {
					Map<String, Object> us = userApiService.getUser(author, user.getCorpId(), "", token);
					if (us != null) {
						a.put("authorName", us.get("userName") + "(匿名)");
					}
				}
			} else {
				if (StringUtils.equals(StringUtils.null2String(author), "1")) {
					a.put("authorName", "系统管理员");
				} else {
					Map<String, Object> us = userApiService.getUser(author, user.getCorpId(), "", token);
					if (us != null) {
						a.put("authorName", us.get("userName"));
					}
				}
			}
			Map<String, String> map1=new HashMap<>();
			if("0".equals(isAnonymity)) {
				map1=this.getImage(author,  user.getCorpId(),  token);
			}else {
				map1.put("fileName", "");
				map1.put("image", "");
			}
			a.putAll(map1);
		}
		/*}*/
		return r;
	}
	
	//获取当前用户的信息(被逻辑删除也能查到)
	public Map findUserName(String id){
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT * from sys_user where id = :id  ");
		//sql.append(" SELECT  is_delete AS isDelete from oa_forum_board where id = :id ");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, paramMap);
		if(list.size() == 0) {
			return null;
		}else {
			return list.get(0);
		}
		
	}

}
